Skip to content

Alamofire

Web & HTTPNetworking/HTTPSwift

What it is

Alamofire is Swift's most widely used HTTP networking library, layering request building, validation, retry and authentication over URLSession.

A Session issues requests built fluently. Responses can be validated and decoded automatically, and an interceptor can adapt or retry requests centrally.

Installation

.package(url: "https://github.com/Alamofire/Alamofire.git", from: "5.10.0")

Getting started

The smallest useful thing you can do with it, and what each part means.

Decoding with async/await
struct Book: Decodable { let id: Int; let title: String }

let books: [Book] = try await AF
    .request("https://api.example.com/books", parameters: ["year": 1990])
    .validate()                       // turn non-2xx into an error
    .serializingDecodable([Book].self)
    .value

let created: Book = try await AF
    .request("https://api.example.com/books",
             method: .post,
             parameters: newBook,
             encoder: JSONParameterEncoder.default)
    .validate()
    .serializingDecodable(Book.self)
    .value
validate() is the line people omit. Without it a 500 response counts as success, and decoding then fails with a confusing type error rather than an HTTP one.

Advanced usage

Where the library earns its place over a simpler alternative.

Interceptors for auth and retry
final class AuthInterceptor: RequestInterceptor {
    func adapt(_ request: URLRequest, for session: Session,
               completion: @escaping (Result<URLRequest, Error>) -> Void) {
        var request = request
        request.setValue("Bearer \(tokenStore.current)", forHTTPHeaderField: "Authorization")
        completion(.success(request))
    }

    func retry(_ request: Request, for session: Session, dueTo error: Error,
               completion: @escaping (RetryResult) -> Void) {
        guard request.response?.statusCode == 401, request.retryCount < 1 else {
            return completion(.doNotRetry)
        }
        Task {
            try await tokenStore.refresh()
            completion(.retry)
        }
    }
}

let session = Session(interceptor: AuthInterceptor())
Centralised token refresh is the strongest reason to use Alamofire over raw URLSession: a 401 refreshes and replays the request once, without every call site handling it.

Errors and fixes

The failures you are most likely to hit, and what actually resolves them.

responseSerializationFailed
The response body does not match the Decodable type. Print the raw data — it is often an HTML error page.
Requests hang after backgrounding
A standard Session is suspended in the background. Use a background URLSessionConfiguration for transfers that must continue.

Best practices

  • Always call validate(); Alamofire does not treat HTTP error statuses as failures otherwise.
  • Create one Session and reuse it — a Session per request loses connection reuse.
  • Put authentication in a RequestInterceptor rather than setting headers at each call site.
  • Consider plain URLSession for simple needs; modern async URLSession covers a lot.

Background

Why it exists, and what it was reacting to.

Alamofire grew out of AFNetworking, the Objective-C standard. URLSession has improved considerably since, so Alamofire's value is now in what it adds around it: interceptors, automatic retry and request adaptation.