Async GET with URLSession
iOS 16.0The modern baseline. No Alamofire needed for this, and most apps never need more.
struct APIClient {
var baseURL: URL
var session: URLSession = .shared
func get<T: Decodable>(_ path: String, as type: T.Type = T.self) async throws -> T {
let (data, response) = try await session.data(from: baseURL.appending(path: path))
guard let http = response as? HTTPURLResponse else { throw APIError.badResponse }
guard (200..<300).contains(http.statusCode) else {
throw APIError.status(http.statusCode)
}
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
return try decoder.decode(T.self, from: data)
}
}
enum APIError: Error {
case badResponse
case status(Int)
}