> ## Documentation Index
> Fetch the complete documentation index at: https://fastapi2day.codewithsiva.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# How the Web Works: HTTP Requests, Responses & Status Codes

> Learn the client-server model, HTTP request anatomy, response status codes, and REST methods before writing a single line of FastAPI code.

Before you write a single line of FastAPI code, it pays to understand the mechanics that govern every conversation between a browser, a mobile app, or any API client and the server sitting on the other side. Every time you load a webpage, log in to an app, or fetch data, your device is participating in the **Client-Server Model** over the **HTTP protocol** — and once you see how it works, building APIs becomes far more intuitive.

***

## The Client-Server Model

The web runs on a simple pattern of exchange. There are two roles — a client that asks for something and a server that responds:

* **Client (The Requester):** Typically a web browser, mobile app, or command-line tool like `curl`. The client initiates communication by sending a **Request**.
* **Server (The Responder):** A computer running software — like your FastAPI application — that listens for incoming requests, processes them (often querying databases), and sends back a **Response**.

```mermaid theme={null}
sequenceDiagram
    actor Client as Client (Browser/App)
    participant Server as Server (FastAPI)

    Client->>Server: HTTP Request (GET /employees)
    Note over Server: Processes request &<br/>fetches employee list
    Server->>Client: HTTP Response (200 OK + JSON Data)
```

<Note>
  Every API interaction you build in this course follows this exact cycle. Understanding it deeply will make every FastAPI concept you learn make immediate sense.
</Note>

***

## Anatomy of an HTTP Request

An HTTP request is a structured text block sent by the client containing four main components:

1. **HTTP Method (Verb):** Tells the server what action to perform (e.g., `GET`, `POST`).
2. **URL / Path:** The specific address of the resource (e.g., `/api/v1/employees`).
3. **Headers:** Key-value pairs containing metadata (e.g., `Content-Type: application/json`, auth tokens).
4. **Body (Payload):** The actual data being sent (e.g., the details of a new employee). `GET` and `DELETE` requests typically do not have bodies.

```mermaid theme={null}
graph TD
    Request["HTTP Request"] --> Method["Method (e.g., POST)"]
    Request --> Path["Path (e.g., /employees)"]
    Request --> Headers["Headers (e.g., Content-Type, Authorization)"]
    Request --> Body["Body (JSON Payload)"]
```

Here is a real example of an HTTP request:

```http theme={null}
POST /employees/101?active=true HTTP/1.1
Host: api.company.com
Content-Type: application/json
Authorization: Bearer <token>

{
    "name": "Siva",
    "department": "IT"
}
```

### URL Breakdown

Every URL contains several components. For the following address:

```text theme={null}
https://api.company.com/employees/101?active=true
```

| Part                | Value             |
| ------------------- | ----------------- |
| **Protocol**        | `https`           |
| **Host**            | `api.company.com` |
| **Endpoint (Path)** | `/employees/101`  |
| **Path Parameter**  | `101`             |
| **Query Parameter** | `active=true`     |

### Full Request Component Reference

| Component           | Example                                       |
| ------------------- | --------------------------------------------- |
| **HTTP Method**     | `POST`                                        |
| **Host**            | `api.company.com`                             |
| **Endpoint (Path)** | `/employees/101`                              |
| **Path Parameter**  | `101`                                         |
| **Query Parameter** | `active=true`                                 |
| **Headers**         | `Content-Type`, `Authorization`, `User-Agent` |
| **Request Body**    | JSON employee data                            |

***

## Anatomy of an HTTP Response

Once the server processes the request, it returns an HTTP response containing:

1. **Status Code:** A three-digit number indicating the outcome (e.g., `200 OK`, `404 Not Found`).
2. **Headers:** Metadata about the response (e.g., `Content-Type: application/json`).
3. **Body:** The requested data, usually formatted as JSON for modern APIs.

```mermaid theme={null}
graph TD
    Response["HTTP Response"] --> Status["Status Code (e.g., 200 OK)"]
    Response --> Headers["Headers (e.g., Content-Type, Set-Cookie)"]
    Response --> Body["Body (JSON, HTML, or File)"]
```

Example response from a weather API:

```http theme={null}
HTTP/1.1 200 OK
Content-Type: application/json

{
    "city": "London",
    "temperature": 18.5,
    "condition": "Partly Cloudy"
}
```

***

## HTTP Methods (Verbs)

HTTP methods define the **semantic action** the client wants to perform on a resource. In RESTful API design, you map these methods to CRUD (Create, Read, Update, Delete) operations:

| HTTP Method  | CRUD Action      | Endpoint Example      | Description                            | Has Body? |
| :----------- | :--------------- | :-------------------- | :------------------------------------- | :-------- |
| **`GET`**    | Read             | `GET /employees`      | Retrieve a list or specific employee.  | No        |
| **`POST`**   | Create           | `POST /employees`     | Create a new employee record.          | **Yes**   |
| **`PUT`**    | Update (Full)    | `PUT /employees/1`    | Completely replace an existing record. | **Yes**   |
| **`PATCH`**  | Update (Partial) | `PATCH /employees/1`  | Partially update details only.         | **Yes**   |
| **`DELETE`** | Delete           | `DELETE /employees/1` | Delete an employee record.             | No        |

***

## API Endpoints and Path Parameters

An **endpoint** is a specific URL where your API provides access to a resource. Here's how a standard Employee API looks:

```text theme={null}
GET    /employees
GET    /employees/101
POST   /employees
PUT    /employees/101
DELETE /employees/101
```

<Accordion title="How do I tell if a URL segment is a path parameter or part of the endpoint?">
  ### Short Answer

  **You cannot tell by looking at the URL alone.** It depends entirely on how the route is defined in the application.

  ### Example

  Consider this URL:

  ```text theme={null}
  https://api.company.com/employees/101
  ```

  Is `101` part of the endpoint, or a path parameter? **You can only know from the route definition.**

  **Case 1: `101` is a path parameter**

  ```python theme={null}
  @app.get("/employees/{employee_id}")
  def get_employee(employee_id: int):
      ...
  ```

  | Component        | Value                      |
  | ---------------- | -------------------------- |
  | Endpoint Pattern | `/employees/{employee_id}` |
  | Requested URL    | `/employees/101`           |
  | Path Parameter   | `employee_id = 101`        |

  **Case 2: `101` is part of the fixed endpoint**

  ```python theme={null}
  @app.get("/employees/101")
  def get_special_employee():
      ...
  ```

  Here `101` is a hard-coded part of the route — there is no path parameter at all.

  ### Key Takeaway

  You must always compare the URL with the **route definition** to determine which parts are parameters.
</Accordion>

***

## HTTP Status Codes

Status codes are grouped by their first digit, letting the client know immediately what kind of outcome occurred.

### 🟢 2xx: Success

* **`200 OK`** — The request succeeded and the server returned the requested data.
* **`201 Created`** — A new resource was successfully created.
* **`204 No Content`** — Success, but no body is returned (common for `DELETE`).

### 🟡 3xx: Redirection

* **`301 Moved Permanently`** / **`307 Temporary Redirect`** — The resource is at a different location.

### 🔴 4xx: Client Errors

* **`400 Bad Request`** — The server could not understand the request (e.g., invalid JSON).
* **`401 Unauthorized`** — Authentication is required (e.g., missing or invalid JWT).
* **`403 Forbidden`** — Authenticated but lacking permission.
* **`404 Not Found`** — The requested resource does not exist.
* **`422 Unprocessable Entity`** — Structure is correct but validation failed (e.g., a Pydantic error).

### 💥 5xx: Server Errors

* **`500 Internal Server Error`** — Something crashed on the server.
* **`503 Service Unavailable`** — The server is overloaded or under maintenance.

<Warning>
  A `401 Unauthorized` means the client isn't authenticated at all. A `403 Forbidden` means they are authenticated but don't have permission. These are different errors and should be used precisely.
</Warning>

***

## REST API Design Conventions

Clean, consistent URLs make your API intuitive to use. Follow these rules when designing your endpoints.

**Use nouns, not verbs. Use plural names. Keep paths lowercase.**

```text theme={null}
✅ GET /students
✅ GET /students/101
✅ GET /student-courses

❌ GET /getStudents
❌ POST /createStudent
❌ GET /studentDetails
```

**Use path parameters to identify a specific resource:**

```http theme={null}
GET /students/101
PUT /students/101
DELETE /students/101
```

**Use query parameters for filtering, sorting, or pagination:**

```http theme={null}
GET /students?department=CSE
GET /students?sort=name&page=1&limit=10
```

<Tip>
  **Rule of thumb:** If the value uniquely *identifies* a resource, use a path parameter. If it *filters or modifies how data is retrieved*, use a query parameter.
</Tip>
