Lesson 7 • Intermediate
Working with APIs 🌐
Fetch data from the internet with URLSession, decode JSON responses with Codable, and build reactive API-driven SwiftUI screens using async/await.
What You'll Learn in This Lesson
- • Make GET and POST requests with URLSession
- • Decode and encode JSON with the Codable protocol
- • Handle API errors gracefully with Swift's error handling
- • Use
async/awaitand parallelasync let - • Integrate API data into SwiftUI views with
.task
1️⃣ URLSession — Making Requests
URLSession is Swift's built-in networking framework. With Swift 5.5's async/await support, making API calls is now clean and readable — no more nested callback pyramids.
Try It: URLSession
GET and POST requests with URLSession
// URLSession — Swift's Built-in Networking
console.log("=== URLSession Basics ===");
console.log("URLSession is Swift's built-in networking API.");
console.log("It handles HTTP requests, downloads, uploads, and WebSockets.");
console.log();
// Show the Swift code structure
console.log("=== GET Request ===");
console.log("func fetchUsers() async throws -> [User] {");
console.log(' let url = URL(string: "https://api.example.com/users")!');
console.log(" let (data, response) = try await URL
...2️⃣ Codable — JSON Magic
Swift's Codable protocol automatically converts between JSON and Swift structs. Just make your model conform to Codable, and JSONDecoder/JSONEncoder handle the rest — including nested objects and arrays.
Try It: Codable
JSON decoding, encoding, nested models, and CodingKeys
// Codable — JSON Encoding & Decoding
console.log("=== Codable Protocol ===");
console.log("Codable = Encodable + Decodable");
console.log("Automatically converts between JSON and Swift objects!");
console.log();
// Simulating Codable
console.log("=== Defining a Codable Model ===");
console.log("struct User: Codable {");
console.log(" let id: Int");
console.log(" let name: String");
console.log(" let email: String");
console.log(" let isActive: Bool");
console.log("}");
console.log(
...3️⃣ Async/Await & Error Handling
Swift's structured concurrency makes async code look like synchronous code. Use async let to run multiple requests in parallel, and Swift's do/catch for type-safe error handling with custom error enums.
Try It: Async Patterns
Sequential vs parallel async, error handling, and SwiftUI integration
// Async/Await & Error Handling in Swift
console.log("=== async/await in Swift ===");
console.log("Swift uses structured concurrency (like Kotlin coroutines).");
console.log();
// Simulating async operations
console.log("=== Sequential Async Calls ===");
console.log("func loadUserProfile() async throws -> Profile {");
console.log(" let user = try await fetchUser(id: 123) // wait for user");
console.log(" let posts = try await fetchPosts(userId: 123) // then wait for posts");
consol
...⚠️ Common Mistakes
httpResponse.statusCode.snake_case and your model uses camelCase, set decoder.keyDecodingStrategy = .convertFromSnakeCase..task modifier in SwiftUI instead of .onAppear — it automatically cancels when the view disappears.📋 Quick Reference — APIs
| Operation | Swift Code |
|---|---|
| GET request | try await URLSession.shared.data(from: url) |
| Decode JSON | JSONDecoder().decode(T.self, from: data) |
| Encode JSON | JSONEncoder().encode(object) |
| Parallel async | async let a = fetch(); async let b = fetch() |
| Error handling | do { try await ... } catch { ... } |
| SwiftUI task | .task { await loadData() } |
🎉 Course Complete!
Congratulations! You've completed the Swift course! You now know the fundamentals of Swift programming, OOP, SwiftUI, and API integration. You're ready to build real iOS apps!
Sign up for free to track which lessons you've completed and get learning reminders.