Fetch JSON with URLSession
Validate HTTP status before decoding the response.
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
struct Todo: Decodable { let id: Int; let title: String }
let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")!
do {
let (data, response) = try await URLSession.shared.data(from: url)
guard let http = response as? HTTPURLResponse,
(200..<300).contains(http.statusCode) else {
throw URLError(.badServerResponse)
}
let todo = try JSONDecoder().decode(Todo.self, from: data)
print(todo.title)
} catch { print("Request failed: \(error)") }How it works
The async data method can return a response for an HTTP error status. Validate status before decoding. FoundationNetworking supplies networking APIs on Linux.
Keep in mind
Network access may be blocked by the compiler sandbox. Run locally if necessary.