Skip to content

Instantly share code, notes, and snippets.

@codewithsanthoshofficial
Created February 10, 2026 18:32
Show Gist options
  • Select an option

  • Save codewithsanthoshofficial/5e6a92c21a2d602a2e82e4e98cccd1ce to your computer and use it in GitHub Desktop.

Select an option

Save codewithsanthoshofficial/5e6a92c21a2d602a2e82e4e98cccd1ce to your computer and use it in GitHub Desktop.
import Foundation
enum HttpMethod:String {
case get = "GET"
case post = "POST"
case put = "PUT"
case delete = "DELETE"
}
enum NetworkError:Error {
case invlaidURL
case serverError(Int)
case decodingError
case unknown
}
class APIService {
static let shared = APIService()
private init(){ }
func request<T:Codable>(endpoint:String, method:HttpMethod = .get, headers: [String: String]? = nil, parameters: [String: Any]? = nil) async throws -> T {
guard let url = URL(string: endpoint) else {
throw URLError(.badURL)
}
var request = URLRequest(url: url)
request.httpMethod = method.rawValue
headers?.forEach {
request.addValue($0.value, forHTTPHeaderField: $0.key)
}
if let parameters {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
}
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpresponse = response as? HTTPURLResponse, (200...299).contains(httpresponse.statusCode) else {
throw URLError(.badServerResponse)
}
return try JSONDecoder().decode(T.self, from: data)
}
}
=======================
import Foundation
enum APIEndPoint {
static let baseURL = "https://newsapi.org/v2/everything?q=tesla&from=2026-01-10&sortBy=publishedAt&apiKey="
case news
var url:String {
switch self {
case .news : return "\(APIEndPoint.baseURL)"
}
}
}
import Foundation
class NewsViewModel:ObservableObject {
@Published var newList:[Articles] = []
init() {
Task {await self.getNews()}
}
@MainActor
func getNews() async {
do {
let response:NewsModelRes = try await APIService.shared.request(endpoint: APIEndPoint.news.url)
self.newList = response.articles ?? []
print(self.newList.count)
}
catch {
print("Request failed:\(error)")
}
}
}
//POST
//let response:NewsModelRes = try await APIService.shared.request(endpoint: APIEndPoint.news.url, method: .put, headers: nil, parameters: [:])
==========================
import Foundation
struct NewsModelRes:Codable {
let status:String?
let totalResults:Int?
let articles:[Articles]?
enum CodingKeys: String, CodingKey {
case status
case totalResults
case articles
}
}
struct Articles:Codable, Identifiable {
var id : String {url ?? ""}
let author: String?
let title: String?
let description: String?
let url: String?
let urlToImage: String?
enum CodingKeys: String, CodingKey {
case author
case title
case description
case url
case urlToImage
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment