Swift Academy · Lesson

URLSession data(from:) with async/await

Fetching data asynchronously from REST APIs using the modern URLSession API.

Lesson 1 of 413 steps

URLSession data(from:) with async/await is a free Swift Academy lesson on CoddyKit. This is lesson 1 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, and your progress syncs across the web and the CoddyKit app. The Swift Academy course includes 4 lessons in total.

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-flight

Uploading 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.

Free to start

Learn Swift with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
122
Lessons
409

Frequently Asked Questions

Is the “URLSession data(from:) with async/await” lesson free?

Yes — any 3 lessons of the Swift Academy learning path, including “URLSession data(from:) with async/await”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Swift Academy course includes 4 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.

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

  1. URLSession data(from:) with async/await
  2. Codable: Encoding and Decoding JSON
  3. Error Handling and HTTP Status Codes
  4. Retry Logic and Background URLSession
← Back to Swift Academy