Networking and APIs

Article · 2:00

URLSession for the request, Codable for turning JSON into Swift types the compiler understands.

URLSession is the networking stack, and for most work you need one method of it: data(from:) or data(for:), which hand back the bytes and the response. There is no third-party library to install - Alamofire exists and is fine, but a course that teaches it first leaves you unable to read the documentation.

Codable is the half that matters more. Conform a type to Decodable and Swift generates the code that reads JSON into it, matching on property names. Where the JSON uses different names, either supply a CodingKeys enum or set the decoder's keyDecodingStrategy to .convertFromSnakeCase and let it map created_at to createdAt for you. Dates need a strategy too; APIs mostly speak ISO 8601.

Two habits separate code that works from code that keeps working. Check the status code - a 404 returns a perfectly valid body full of error JSON, and without the check you will see a decoding error and go looking in the wrong place. And let decoding errors reach you in development: DecodingError says exactly which key was missing or the wrong type, and swallowing it into a generic "something went wrong" throws away the only useful information in the failure.

import Foundation

// The shape you want, not the shape the API happens to send.
struct Article: Decodable, Identifiable {
    let id: Int
    let title: String
    let publishedAt: Date       // from "published_at"
    let author: Author

    struct Author: Decodable {
        let name: String
    }
}

enum APIError: Error {
    case badStatus(Int)
    case decoding(DecodingError)
}

func fetchArticles() async throws -> [Article] {
    let url = URL(string: "https://example.com/api/articles")!

    let (data, response) = try await URLSession.shared.data(from: url)

    // Check the status FIRST. A 404 body decodes badly and misleads you.
    guard let http = response as? HTTPURLResponse else {
        throw URLError(.badServerResponse)
    }
    guard (200..<300).contains(http.statusCode) else {
        throw APIError.badStatus(http.statusCode)
    }

    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    decoder.dateDecodingStrategy = .iso8601

    do {
        return try decoder.decode([Article].self, from: data)
    } catch let error as DecodingError {
        // Keep the detail: it names the key and the type that disagreed.
        throw APIError.decoding(error)
    }
}