Courses/Swift/Working with APIs

    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/await and parallel async 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

    Try it Yourself »
    JavaScript
    // 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

    Try it Yourself »
    JavaScript
    // 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

    Try it Yourself »
    JavaScript
    // 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

    ⚠️
    Not checking HTTP status codes — URLSession doesn't throw on 404 or 500 errors. Always check httpResponse.statusCode.
    ⚠️
    JSON key mismatch — If the API uses snake_case and your model uses camelCase, set decoder.keyDecodingStrategy = .convertFromSnakeCase.
    💡
    Pro Tip: Use .task modifier in SwiftUI instead of .onAppear — it automatically cancels when the view disappears.

    📋 Quick Reference — APIs

    OperationSwift Code
    GET requesttry await URLSession.shared.data(from: url)
    Decode JSONJSONDecoder().decode(T.self, from: data)
    Encode JSONJSONEncoder().encode(object)
    Parallel asyncasync let a = fetch(); async let b = fetch()
    Error handlingdo { 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.

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service