Make network requests with Alamofire
Alamofire gives Swift developers a compact way to send HTTP requests, encode parameters, download files and handle responses. Instead of assembling every URLRequest by hand, you can begin with AF.request, then add validation, headers or a serialiser while keeping the code readable. That is useful in personal projects because a small API client should not distract from the feature you are trying to learn.
Learning the library becomes easier when each request has a clear purpose: fetch JSON, upload a file or turn a server response into a Swift model. I built my first networking layer while moving between coding sessions around Atyrau and testing ideas on an iPad. Australian developers may recognise the rhythm of coding on a Sydney train, during a Melbourne café break or while travelling through regional Australia, where connectivity can vary sharply; a calm “no worries” message can keep failure handling friendly.
Install Alamofire in Xcode
Alamofire is distributed through Swift Package Manager. In Xcode, select File, Add Package Dependencies, provide the package repository address and choose a version that supports your deployment target. Add the package to the app target, then import it once:
import Alamofire
If dependency setup feels premature while you are learning syntax, Askar's guide to Swift Playgrounds on iPad offers a low-pressure way to practise Codable and asynchronous code. Keep networking practice separate from the package dependency: define and decode one small model in a playground first, then move the same type into the Xcode project.
Keep the package version consistent across your project and personal devices. Before moving to a complex client, run a basic request against a public API and confirm that your app can print the decoded value.
Send and decode a request
Begin with a small endpoint and a model that matches the JSON. Codable removes most of the manual dictionary work:
struct User: Decodable {
let id: Int
let name: String
let city: String
}
@MainActor
func fetchUser(id: Int) async {
let url = "https://api.example.com/users/\(id)"
do {
let user = try await AF.request(url)
.validate(statusCode: 200..<300)
.serializingDecodable(User.self)
.value
print(user.name)
} catch {
print("Request failed: \(error.localizedDescription)")
}
}
The chain has three useful stages. AF.request creates a DataRequest; validate turns an unexpected status code into a failure; serializingDecodable passes the body through JSONDecoder and returns the model. Because value is asynchronous, it must be awaited inside a Task.
@MainActor keeps the fetched value safe to use directly when updating SwiftUI or UIKit views. Handle the error at the call site rather than hiding it, since transport failures, server failures and malformed payloads require different responses.
Send parameters, JSON and headers
Query parameters belong in the URL for a GET request. Alamofire can build them from a dictionary:
AF.request(
"https://api.example.com/events",
method: .get,
parameters: ["city": "Melbourne", "page": 1],
encoder: URLEncoding.default
)
For a create or update operation, send an Encodable payload as JSON. Headers such as an authorisation token are added to the same request:
struct EventDraft: Encodable {
let title: String
let startsAt: String
}
let headers = HTTPHeaders()
headers.add(.authorization(bearerToken: token))
let draft = EventDraft(
title: "Swift meetup",
startsAt: "2026-11-08T09:00:00+11:00"
)
let data = try await AF.request(
"https://api.example.com/events",
method: .post,
parameters: draft,
encoder: JSONParameterEncoder.default,
headers: headers
)
.validate(statusCode: 200..<300)
.serializingData()
.value
URLEncoding.default is useful for form-style query strings, while JSONParameterEncoder.default creates a JSON body and its Content-Type header. Never embed an API secret in an iOS binary: treat the client token as public, restrict it on the server and refresh it through the platform's secure storage.
Compare Alamofire with URLSession
Alamofire is a layer above Foundation's networking APIs, not a replacement for them. Both can use Swift concurrency, but they expose different levels of convenience:
| Concern | Alamofire | URLSession |
|---|---|---|
| Dependency | Added through Swift Package Manager | Built into Apple platforms |
| Basic request | AF.request with a response serialiser |
URLSession.shared.data(for:) |
| JSON decoding | serializingDecodable(Model.self) |
Decode returned Data with JSONDecoder |
| File transfer | Upload and download conveniences | Upload or download tasks with delegate control |
| Configuration | Chainable defaults and shared helpers | Explicit URLSessionConfiguration options |
| Failure handling | AFError with underlying and validation causes |
URLError, status checks and custom decoding errors |
Choose Alamofire when readable chains, shared configuration and ready-made response serialisers will remove repetition. Stay with URLSession when a small dependency and direct control over session configuration, delegate behaviour or caching matter more. Background uploads can use either approach.
For a learner, the important skill is understanding the underlying HTTP request. Inspect a request in a debugging proxy, confirm its method, query items, headers and body, then map each part to Alamofire's chain. That knowledge transfers cleanly if you later replace the library.
Recommendations for dependable API requests
Networking becomes fragile when error handling is treated as one generic message. Distinguish an unreachable server, a rejected status code, a cancelled task and a decoding mismatch. Alamofire's AFError preserves many of those causes, while your app decides which details to reveal.
AF.request(url)
.validate(statusCode: 200..<300)
.responseDecodable(of: User.self) { response in
switch response.result {
case .success(let user):
print(user.name)
case .failure(let error):
print(error.localizedDescription)
}
}
The following practices keep a personal app predictable without turning it into a large framework:
- Centralise configuration: keep the base URL, endpoint paths and common headers in one place.
- Validate every response: treat only expected 2xx statuses as success and map 401, 404, 429 and 5xx separately.
- Decode into domain models: use
Codablerather than passing loosely typed dictionaries through the view layer. - Set limits and support cancellation: configure timeouts and cancel obsolete work when its screen disappears.
- Redact diagnostic logs: record status codes and request identifiers, never tokens or personal details.
For an Australian audience, money should be returned in AUD and the product should say whether GST is included before checkout. Australian customers generally expect GST-inclusive consumer pricing. Use en_AU for displayed dates and numbers, and store the IANA time-zone identifier rather than a fixed UTC offset.
Turn the client into a shippable feature
A useful first project is an events client for a community app. Fetch a page of events, decode each item into an Event model and display loading, empty and failure states. Start with one endpoint rather than pretending to design every possible route.
This small scope suits how a personal project should grow: first make one request reliable, then add pagination and caching. For an Australian deployment, the API should send ISO 8601 timestamps with an IANA zone such as Australia/Sydney or Australia/Perth, while the interface formats them for the user's locale. That prevents a wall-clock event time from shifting when daylight-saving rules change.
Create an XCTest target named NetworkTests, add one test that feeds the client malformed JSON and checks the message We could not read this response. Please try again., then run it with Command-U in Xcode.