Back to blog

Typesafe API calls in Swift: Generating Alamofire Handlers with quicktype

Alamofire is an elegant HTTP networking library that makes working with JSON APIs in Swift a breeze. quicktype makes Alamofire even more awesome by generating extensions and Codables for typesafe API calls.

Alamofire is an elegant HTTP networking library that makes working with JSON APIs in Swift a breeze. quicktype makes Alamofire even more awesome by generating extensions and Codables for typesafe API calls.

The Traditional Way

Without quicktype, calling an API with Alamofire looks like this:

Alamofire.request("https://api.example.com/users/1")
    .responseJSON { response in
        guard let json = response.value as? [String: Any],
              let name = json["name"] as? String,
              let email = json["email"] as? String else {
            return
        }
        // Use name and email...
    }

This is error-prone, verbose, and lacks type safety.

The quicktype Way

With quicktype-generated code:

Alamofire.request("https://api.example.com/users/1")
    .responseUser { response in
        guard let user = response.value else { return }
        print(user.name)  // Type-safe!
        print(user.email) // Autocomplete works!
    }

Getting Started

  1. Generate Swift code with Alamofire extensions:
quicktype https://api.example.com/users/1 \
    --lang swift \
    --alamofire \
    -o User.swift
  1. Add the generated file to your project

  2. Call your API with type safety!

Generated Code

quicktype generates:

  • Codable structs for your JSON
  • Alamofire response handlers
  • Convenience extensions
struct User: Codable {
    let id: Int
    let name: String
    let email: String
}

extension DataRequest {
    @discardableResult
    func responseUser(
        completionHandler: @escaping (DataResponse<User>) -> Void
    ) -> Self {
        return responseDecodable(completionHandler: completionHandler)
    }
}

Enjoy type-safe, autocomplete-friendly API calls!