URLSession data(from:) with async/await
Fetching data asynchronously from REST APIs using the modern URLSession API.
URLSession data(from:) with async/await is a free Swift Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Modern URLSession API
Swift 5.5+ ships async overloads on URLSession: data(from:delegate:) that suspend instead of using callbacks.
let (data, response) = try await URLSession.shared.data(from: URL(string: "https://api.example.com/items")!)Full Fetch Function
Wrap the call in an async throwing function to make it composable and testable.
func fetchItems() async throws -> [Item] {
let url = URL(string: "https://api.example.com/items")!
let (data, _) = try await URLSession.shared.data(from: url)
return try JSONDecoder().decode([Item].self, from: data)
}Calling from SwiftUI
Call async functions from .task modifier or Task { } inside a button action.
struct ItemList: View {
@State private var items: [Item] = []
var body: some View {
List(items, id: \.id) { Text($0.name) }
.task { items = (try? await fetchItems()) ?? [] }
}
}URLRequest for Custom Headers
Build a URLRequest with method, headers, and body, then pass to data(for:).
var request = URLRequest(url: URL(string: "https://api.example.com/login")!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try? JSONEncoder().encode(LoginBody(email: "a@b.com", password: "pass"))
let (data, _) = try await URLSession.shared.data(for: request)Checking HTTP Status
Cast the response to HTTPURLResponse and verify the status code before decoding.
let (data, response) = try await URLSession.shared.data(from: url)
guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
throw URLError(.badServerResponse)
}
let item = try JSONDecoder().decode(Item.self, from: data)Cancellation
Cancelling the parent Task automatically cancels the in-flight URLSession request.
let task = Task {
let items = try await fetchItems()
// ...
}
task.cancel() // cancels URLSession request if in-flightUploading Data
Use upload(for:from:) to POST binary data or form uploads asynchronously.
var request = URLRequest(url: uploadURL)
request.httpMethod = "POST"
let (data, _) = try await URLSession.shared.upload(for: request, from: imageData)Downloading Files
download(from:) downloads a file to a temporary URL on disk instead of into memory.
let (fileURL, _) = try await URLSession.shared.download(from: remoteURL)
let destURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("file.pdf")
try FileManager.default.moveItem(at: fileURL, to: destURL)Custom URLSession Configuration
Create a custom session with timeouts, caching policy, and background support.
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 30
config.requestCachePolicy = .reloadIgnoringLocalCacheData
let session = URLSession(configuration: config)async bytes for Streaming
Use bytes(from:) to stream response data line by line without buffering the entire response.
let (stream, _) = try await URLSession.shared.bytes(from: url)
for try await line in stream.lines {
print(line)
}Testing with URLProtocol
Mock network responses in tests by subclassing URLProtocol and injecting it into a custom session configuration.
class MockURLProtocol: URLProtocol {
static var requestHandler: ((URLRequest) throws -> (HTTPURLResponse, Data))?
// override canInit, startLoading, stopLoading
}Quick Check
Which async URLSession method downloads a URL response directly to a temporary file on disk?
Lesson Recap
Use URLSession.shared.data(from:) for async GET requests, data(for:) with custom URLRequest for POST/PUT, download(from:) for file downloads, and bytes(from:) for streaming. Always check the HTTP status code before decoding.
Frequently asked questions
Is the “URLSession data(from:) with async/await” lesson free?
Yes — the full text of “URLSession data(from:) with async/await” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.
What will I learn in “URLSession data(from:) with async/await”?
Fetching data asynchronously from REST APIs using the modern URLSession API. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Swift Academy?
No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “URLSession data(from:) with async/await” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Swift Academy lesson?
Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- URLSession data(from:) with async/await
- Codable: Encoding and Decoding JSON
- Error Handling and HTTP Status Codes
- Retry Logic and Background URLSession