> For the complete documentation index, see [llms.txt](https://ios-course.cornellappdev.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ios-course.cornellappdev.com/course-content/lectures/l8-networking-i/pre-lecture-8-reading.md).

# Pre-Lecture 8 Reading

FA 2026

TLDR — Most apps talk to a **server**. They do this over **HTTP**, sending requests and getting back **JSON**. In Swift, we use `URLSession` with `async/await` to make these calls without freezing the UI, and the `Codable` protocol to convert JSON into Swift structs.

### Clients & Servers

A **client** is anything that asks for data—your iPhone, a laptop, a browser. A **server** is what answers. When you open Instagram, your phone (client) asks Instagram’s server for your feed, and the server sends back the posts.

Apps that rely on a server include social media, multiplayer games, and campus apps like Eatery. Apps that *don’t* need one—like the Camera app or Notes—work entirely on-device.

**Key Takeaway**: If your app shows *data* that lives somewhere else (another user's post, a menu, a leaderboard), it needs **networking**.

***

### HTTP Requests

HTTP (HyperText Transfer Protocol) is the language clients and servers use to talk. A client sends a **request**, and the server sends back a **response** with a status code.

#### Request Methods

The four most common methods are `GET` (read data), `POST` (create data), `PUT` (update data), and `DELETE` (remove data). In this lecture we’ll focus on `GET` and `POST`.

#### Status Codes

Every HTTP response comes with a numeric status code. Here’s what each range means:

<table><thead><tr><th width="98.1953125">Code</th><th width="169.26171875">Category</th><th width="468.125">What it means</th></tr></thead><tbody><tr><td>1XX</td><td><mark style="color:$warning;">Info</mark></td><td>Request received, still processing</td></tr><tr><td>2XX</td><td><mark style="color:$success;">Success</mark></td><td>Everything worked (200 OK is the most common)</td></tr><tr><td>3XX</td><td><mark style="color:$primary;">Redirect</mark></td><td>Resource moved somewhere else</td></tr><tr><td>4XX</td><td><mark style="color:$danger;">Client Error</mark></td><td>Something wrong with your request (404 = not found)</td></tr><tr><td>5XX</td><td><mark style="color:$danger;">Server Error</mark></td><td>Server broke trying to handle a valid request</td></tr></tbody></table>

***

### JSON

JSON (JavaScript Object Notation) is the standard format for sending data over HTTP. It’s just key-value pairs—similar to a Swift dictionary. Keys are always strings; values can be strings, numbers, booleans, arrays, objects, or `null`.

```json
{
  "age": 19,
  "classes": ["CS 1998", "PHYS 2213"],
  "major": "Info Sci",
  "name": "Vin Bui"
}
```

Notice how this maps almost directly to a Swift struct with properties `age: Int`, `classes: [String]`, `major: String`, and `name: String`. That’s the whole idea—JSON is the bridge between the server’s data and your Swift model.

***

### Networking in Swift

#### Why async/await?

Network requests take time—maybe milliseconds, maybe seconds. If we waited synchronously, the entire UI would freeze. Swift’s `async/await` (introduced in Swift 5.5) lets us “pause” a function in the background until the data arrives, without blocking the main thread.

**Analogy**

Think of it like ordering food at a restaurant. You place your order (send the request), then keep chatting with friends (the app stays responsive) until the waiter brings the food back (the response arrives).

#### A GET Request

Here’s the basic pattern for fetching data from a server:

```swift
func fetchPosts() async throws -> [Post] {
    let url = URL(string: "https://api.example.com/posts")!
    let (data, _) = try await URLSession.shared.data(from: url)
    let posts = try JSONDecoder().decode([Post].self, from: data)
    return posts
}
```

Three steps happen here:

**1.** Build a `URL` from a string. **2.** Use `URLSession.shared.data(from:)` to fire the request and `await` the response. **3.** Decode the raw `Data` into your Swift model with `JSONDecoder`.

#### Calling it from a View

```swift
struct FeedView: View {
    @State private var posts: [Post] = []

    var body: some View {
        List(posts, id: \.username) { post in
            Text("\(post.username) posted a new photo!")
        }
        .task {
            do {
                posts = try await fetchPosts()
            } catch {
                print("Failed to fetch posts: \(error)")
            }
        }
    }
}
```

The `.task` modifier kicks off the async work when the view appears. Because it runs asynchronously, the list can render immediately (empty at first) and populate once the data arrives.

***

### Codable

`Codable` is a protocol (actually a typealias for `Decodable & Encodable`) that tells Swift how to convert between JSON and your structs. If the JSON keys match your property names, you get automatic decoding for free:

```swift
struct Student: Codable {
    let age: Int
    let classes: [String]
    let firstName: String
    let lastName: String
    let major: String
}
```

{% hint style="danger" %}
**Watch Out: snake\_case vs. camelCase**

APIs often use `snake_case` keys (e.g. `"first_name"`) while Swift uses `camelCase` (e.g. `firstName`). To handle this automatically, set the decoder’s key strategy:

```
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
```

{% endhint %}
