Networking with URLSession
Prerequisites: Codable and JSON
URLSession (from Foundation) makes HTTP requests. Combined with
Codable and async/await, fetching data from an API takes only a
few lines.
async and await get a full treatment in Level 3. For now: a network
call takes time, await marks the point where your code waits for
it without freezing the program, and functions that wait are marked
async.
A GET request
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking // needed for URLSession on Linux
#endif
struct Repo: Decodable {
let fullName: String
let stargazersCount: Int
}
enum APIError: Error {
case badStatus(Int)
}
func fetchRepo(_ name: String) async throws -> Repo {
let url = URL(string: "https://api.github.com/repos/\(name)")!
let (data, response) = try await URLSession.shared.data(from: url)
if let http = response as? HTTPURLResponse, !(200..<300).contains(http.statusCode) {
throw APIError.badStatus(http.statusCode)
}
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
return try decoder.decode(Repo.self, from: data)
}
do {
let repo = try await fetchRepo("swiftlang/swift")
print("\(repo.fullName) has \(repo.stargazersCount) stars")
} catch {
print("Request failed: \(error)")
}
swiftlang/swift has 68734 stars
(The number will be different when you run it.)
data(from:)returns the body and the response. It throws for network failures — no connection, timeout, invalid host.- A 404 or 500 is not a thrown error — the request succeeded at the
network level. Always check
statusCodeyourself. - Top-level code in a script can use
awaitdirectly.
POST with JSON and headers
var request = URLRequest(url: URL(string: "https://httpbin.org/post")!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.timeoutInterval = 10
request.httpBody = try JSONEncoder().encode(["title": "Hello"])
let (_, response) = try await URLSession.shared.data(for: request)
print((response as? HTTPURLResponse)?.statusCode ?? 0)
200
Apps and HTTPS
Apple platforms require HTTPS for network requests by default (App
Transport Security). Keep it that way — plain http:// sends data
unencrypted.
Common mistakes
- Treating any response as success without checking the status code.
- Putting API keys in app source code. Anything shipped inside an app can be extracted; keep secrets on your server.