A testable API client in Swift: endpoint model, typed errors and token refresh
In most iOS apps, networking code starts small: a URLSession.shared.data(from:) call in a view model, followed by a JSONDecoder. When the second screen arrives, the code gets copied; on the third, an authorization header is added; on the fourth, someone notices a 401 response and writes a patch to refresh the session. After a while every screen handles network errors differently, and none of it can be tested.
In this post I walk through a practical way to build a small but solid API client in Swift: defining endpoints as data, sending every request through a single point, turning errors into meaningful types, refreshing the token only once across concurrent requests, and testing all of it without touching the real network. The goal is not to write a library; it is to make sure the rest of the app does not have to know about networking details.
Defining the endpoint as data
The first step is to express what each request looks like as a value. The path, HTTP method, query parameters, body and response type are gathered in a single structure:
struct Endpoint<Response: Decodable> {
var method = "GET"
var path: String
var query: [URLQueryItem] = []
var body: Data? = nil
var requiresAuth = true
}
enum Endpoints {
static func orders(page: Int) -> Endpoint<[Order]> {
Endpoint(path: "/orders",
query: [URLQueryItem(name: "page", value: String(page))])
}
static func cancelOrder(id: Order.ID) -> Endpoint<Order> {
Endpoint(method: "POST", path: "/orders/\(id)/cancel")
}
}
Thanks to the generic Response parameter, the caller does not have to state the return type separately; orders(page:) always returns [Order]. Because endpoints are just data, they can be inspected and tested without a network: a simple unit test can check that the right path and parameters are produced.
For responses without a body (for example a delete request returning 204), defining an empty Decodable type and handling it specially in the client is tidier than writing a separate method for each endpoint.
A single sending point for all requests
Once the endpoints are defined, you write a client that sends all of them through the same path. URL construction, common headers, authorization, status code checks and decoding happen here, once:
final class APIClient {
private let baseURL: URL
private let session: URLSession
private let tokens: TokenStore
private let decoder: JSONDecoder
init(baseURL: URL, session: URLSession, tokens: TokenStore) {
self.baseURL = baseURL
self.session = session
self.tokens = tokens
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
self.decoder = decoder
}
func send<R>(_ endpoint: Endpoint<R>) async throws -> R {
let data = try await perform(endpoint, retryOnUnauthorized: true)
do {
return try decoder.decode(R.self, from: data)
} catch let error as DecodingError {
throw APIError.decoding(error)
}
}
}
The URLSession is injected from outside; this is the key to using a different session configuration in tests. The JSONDecoder settings also live in one place. When the date format or key conversion strategy is set separately in each view model, a small change on the server can break half the app.
Making errors typed and meaningful
URLSession only throws for connection-level problems. From its point of view, a 404 or 500 from the server is a successful response. That is why checking status codes and translating the result into an error type the app understands is the client's job:
enum APIError: Error {
case transport(URLError)
case unauthorized
case server(status: Int, problem: ProblemDetails?)
case decoding(DecodingError)
}
This distinction pays off directly in the UI. transport is usually a connectivity problem, and a "try again" button makes sense. unauthorized means the session has really ended and the user needs to be sent to the sign-in screen. In the server case, if the server returned an error body (for example in Problem Details format), you can turn it into a suitable message for the user. decoding, on the other hand, is not something to show the user; it is a contract mismatch you need to fix, and logging it matters.
Cancellation should be handled separately. When the user leaves a screen, cancelling the task is not an error and no error message should appear. Since URLSession throws URLError.cancelled in that case, converting it to CancellationError lets upper layers check a single condition:
private func fetch(_ request: URLRequest) async throws -> (Data, URLResponse) {
do {
return try await session.data(for: request)
} catch let error as URLError where error.code == .cancelled {
throw CancellationError()
} catch let error as URLError {
throw APIError.transport(error)
}
}
Refreshing the token only once
In an app that uses short-lived access tokens, the server returns 401 when the token expires. The client obtains a new access token with the refresh token and retries the request once. The problem appears when several requests are in flight at the same time: if three requests get a 401 together while a screen is opening, three separate refresh requests are sent. With servers that rotate the refresh token on every use, this means the second and third refreshes fail and the user gets signed out.
In Swift, an actor is a good tool for this. The ongoing refresh is stored as a Task, and later callers await the result of the same task:
actor TokenStore {
private var accessToken: String?
private var refreshTask: Task<String, Error>?
private let refresher: @Sendable () async throws -> String
init(refresher: @escaping @Sendable () async throws -> String) {
self.refresher = refresher
}
func validToken() async throws -> String {
if let refreshTask { return try await refreshTask.value }
if let accessToken { return accessToken }
return try await refresh(rejected: nil)
}
func refresh(rejected: String?) async throws -> String {
if let refreshTask { return try await refreshTask.value }
if let accessToken, accessToken != rejected { return accessToken }
let task = Task { try await refresher() }
refreshTask = task
defer { refreshTask = nil }
let token = try await task.value
accessToken = token
return token
}
}
The rejected parameter is an important detail. When a request gets a 401 with an old token, another request may already have completed the refresh in the meantime. In that case the current token is returned instead of refreshing again. Keep in mind that an actor is reentrant at its await points; that is why re-checking state after every await is necessary.
On the client side, a 401 is retried only once. If a 401 still comes back after the refresh, the session is truly invalid, and instead of looping, unauthorized is thrown:
private func perform<R>(_ endpoint: Endpoint<R>,
retryOnUnauthorized: Bool) async throws -> Data {
var request = makeRequest(endpoint)
var usedToken: String?
if endpoint.requiresAuth {
let token = try await tokens.validToken()
usedToken = token
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
}
let (data, response) = try await fetch(request)
guard let http = response as? HTTPURLResponse else {
throw APIError.server(status: -1, problem: nil)
}
switch http.statusCode {
case 200..<300:
return data
case 401:
if retryOnUnauthorized, let usedToken {
_ = try await tokens.refresh(rejected: usedToken)
return try await perform(endpoint, retryOnUnauthorized: false)
}
throw APIError.unauthorized
default:
let problem = try? decoder.decode(ProblemDetails.self, from: data)
throw APIError.server(status: http.statusCode, problem: problem)
}
}
If the refresh itself fails, throwing APIError.unauthorized from inside refresher lets the upper layer catch the end-of-session case in one place.
Testing without the real network using URLProtocol
The most reliable way to test the network layer is not to write a protocol that imitates URLSession, but to use the real URLSession and stop requests from reaching the network. URLProtocol does exactly that: a subclass added to the session configuration intercepts every request and returns the response you specify.
final class StubURLProtocol: URLProtocol {
static var handler: ((URLRequest) throws -> (HTTPURLResponse, Data))?
override class func canInit(with request: URLRequest) -> Bool { true }
override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
override func startLoading() {
guard let handler = Self.handler else { return }
do {
let (response, data) = try handler(request)
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
client?.urlProtocol(self, didLoad: data)
client?.urlProtocolDidFinishLoading(self)
} catch {
client?.urlProtocol(self, didFailWithError: error)
}
}
override func stopLoading() {}
}
let config = URLSessionConfiguration.ephemeral
config.protocolClasses = [StubURLProtocol.self]
let session = URLSession(configuration: config)
With this setup you can, for example, build a scenario where the first request returns 401 and returns 200 after the refresh, and verify that the token refresher is called exactly once. Likewise, it becomes easy to test that the client produces the correct APIError when the server returns 422 with a Problem Details body, or that an unexpected JSON field leads to a decoding error.
Two details deserve attention. First, inside URLProtocol the request body usually arrives not as httpBody but as httpBodyStream; if you want to verify the body, you need to read the stream. Second, because handler is a static variable, running these tests in parallel can make them interfere with each other. Running the tests serially, or choosing the handler based on a test identifier in a request header, removes the problem.
The boundary with the view layer
Once the client is in place, view models should not use APIClient directly but a small interface that belongs to your domain. For example, a protocol named OrdersRepository offers orders(page:) and cancel(id:) methods; its real implementation calls APIClient. In view model tests, a simple fake implementation of this protocol is enough, and HTTP details never leak into those tests.
This layering also simplifies error presentation. The view model silently ignores CancellationError, notifies the session manager when APIError.unauthorized arrives, and in other cases shows the user a clear message and a retry option. Instead of every screen making these decisions on its own, they all follow the same contract.
Closing
A good network layer does not draw attention to itself; the rest of the app knows it only as "call this endpoint, get the result or a meaningful error." Defining endpoints as data, sending all requests through one path, expressing errors as types and concentrating token refresh in a single actor provide that simplicity. Tests written with URLProtocol help catch the most fragile scenarios, concurrent 401s, unexpected responses and cancellations, before a release. It may look like a bit more code at the start, but from the second screen onward it pays for itself many times over.