1. HTTP, REST APIs & External Services
HTTP, RESTful API Design & JSON Payloads
Learn how modern Python backends communicate over HTTP: resource-oriented REST URLs, HTTP methods, idempotency, status codes, headers, and clean JSON contracts.
- Design clean resource-oriented REST endpoints using nouns and HTTP verbs
- Choose accurate HTTP status codes (200, 201, 204, 400, 401, 404, 422, 500)
- Understand idempotency and serialize/deserialize JSON payloads cleanly in Python
Every mobile app, React/Next.js frontend, and AI integration talks to backend servers over HTTP exchanging JSON. Before writing your first API route or client script, you need a crisp mental model of the full HTTP request lifecycle and how REST APIs structure URLs, verbs, status codes, and JSON contracts.
1. Architecture & The Full HTTP Request Lifecycle
When a frontend calls your backend, a single fetch() passes through a predictable pipeline before returning JSON:
1. HTTP Request
Method + URL + JSON
2. Auth & CORS
401 / 403 guard
3. Pydantic Schema
422 on bad fields
4. Route + Repo
Depends(get_db) + SQL ?
5. Public JSON
200 / 201 / 204
Every request passes through security/validation gates before touching SQLite, and returns only safe response_model fields.
Every HTTP message has two parts:
- Metadata — the HTTP method + path (or status code in a response) plus Headers such as
Content-Type: application/json,Accept: application/json, andAuthorization: Bearer <token>. - Body (Payload) — optional UTF-8 text (typically JSON) carried by
POST,PUT,PATCH, and most responses.
2. Resource-Oriented URLs, HTTP Verbs & Idempotency
In REST, URLs identify plural nouns (resources)—not actions—while the HTTP method tells the server what action to perform:
| HTTP Method | URL Pattern | Action | Request Body? | Idempotent? |
|---|---|---|---|---|
GET | /courses or /courses/42 | Read a list or single resource | No | Yes |
POST | /courses | Create a new resource | Yes | No (creates a new row each call) |
PUT | /courses/42 | Replace an entire resource | Yes (full object) | Yes |
PATCH | /courses/42 | Partially update specific fields | Yes (changed fields) | Yes (for field sets) |
DELETE | /courses/42 | Remove a resource | No | Yes |
Idempotent means sending the exact same request 1 time or 5 times leaves the server in the same final state. Calling DELETE /courses/42 twice still leaves course 42 absent; calling POST /orders twice would create two separate orders unless an explicit Idempotency-Key header is checked!
PUT vs PATCH: Full Replacement vs Partial Update
PUT /courses/42replaces the entire representation at/courses/42. Every required field (title,level,hours) must be included, or omitted fields are reset/rejected.PATCH /courses/42sends only the fields to change—for example,{"level": "Advanced"}leavestitleandhoursuntouched. Most modern JSON APIs preferPATCHfor edits because clients don't have to re-send every column.
Avoid RPC-style URLs like /getCourse?id=42 or /createNewUser. Use plural nouns (GET /courses/42, POST /users) so HTTP semantics, caching, and developer tooling work consistently.
3. Status Codes Every Backend Developer Uses
Never return 200 OK with {"error": "Not found"}! Frontends, monitoring alerts, and HTTP clients branch on the numeric status code:
| Code | Name | When to Return It |
|---|---|---|
200 | OK | Successful GET, PUT, or PATCH returning JSON |
201 | Created | Successful POST that created a new resource |
204 | No Content | Successful DELETE (empty body—do not send JSON!) |
400 | Bad Request | Malformed syntax (e.g., broken JSON) or invalid business state |
401 | Unauthorized | Missing, malformed, or expired authentication credentials |
403 | Forbidden | Authenticated user lacks permission for this action or resource |
404 | Not Found | Requested resource ID or route does not exist |
409 | Conflict | Unique constraint violation (e.g., email already registered) |
422 | Unprocessable Entity | Valid JSON syntax, but field types/constraints failed validation |
500 | Internal Server Error | Unhandled server exception (never expose raw tracebacks!) |
Use 401 when the server does not know who you are (missing/expired token) and 403 when it knows who you are, but forbids the action (student trying to delete an instructor's course). Similarly, 400 is for unparseable syntax/request structure, whereas 422 (FastAPI's Pydantic default) means JSON parsed cleanly but failed field validation rules.
4. Working with JSON Payloads in Python
Python's json module converts between Python dict/list objects and UTF-8 JSON strings sent over the wire:
import json
payload = {
"id": 101,
"title": "Python Backend",
"published": True,
"instructor": None,
"tags": ["fastapi", "sqlite"],
}
wire_text = json.dumps(payload) # True -> true, None -> null
parsed = json.loads(wire_text) # JSON string -> Python dict
print(parsed["title"], parsed["published"], parsed["instructor"])Notice how JSON types map to Python: JSON objects become dict, arrays become list, true/false become bool, and null becomes None. Timestamps and UUID objects are not natively JSON-serializable in json.dumps()—convert dates to ISO-8601 strings ("2026-11-30T10:00:00Z") before sending.
Try It Yourself in the Playground
Test building a mini REST router/dispatcher in pure Python to see how method + path + JSON body map to status codes (including PUT vs PATCH and malformed JSON 400 handling):
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Add support for DELETE /courses/<id> to handle_request above so deleting an existing ID removes it from COURSES and returns (204, ""), while a missing ID returns (404, json.dumps({"detail": "Course not found"})).
Quick Checkpoints
Which HTTP status code should a POST /users endpoint return when it successfully creates a new user?
Why is POST considered non-idempotent compared to GET or DELETE?