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.

6 min readUpdated 2026-11-30
In This Lesson
  • 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:

FastAPI Request-to-Database Lifecycle

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:

  1. Metadata — the HTTP method + path (or status code in a response) plus Headers such as Content-Type: application/json, Accept: application/json, and Authorization: Bearer <token>.
  2. 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 MethodURL PatternActionRequest Body?Idempotent?
GET/courses or /courses/42Read a list or single resourceNoYes
POST/coursesCreate a new resourceYesNo (creates a new row each call)
PUT/courses/42Replace an entire resourceYes (full object)Yes
PATCH/courses/42Partially update specific fieldsYes (changed fields)Yes (for field sets)
DELETE/courses/42Remove a resourceNoYes

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/42 replaces the entire representation at /courses/42. Every required field (title, level, hours) must be included, or omitted fields are reset/rejected.
  • PATCH /courses/42 sends only the fields to change—for example, {"level": "Advanced"} leaves title and hours untouched. Most modern JSON APIs prefer PATCH for edits because clients don't have to re-send every column.
Avoid Verbs in REST URLs

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:

CodeNameWhen to Return It
200OKSuccessful GET, PUT, or PATCH returning JSON
201CreatedSuccessful POST that created a new resource
204No ContentSuccessful DELETE (empty body—do not send JSON!)
400Bad RequestMalformed syntax (e.g., broken JSON) or invalid business state
401UnauthorizedMissing, malformed, or expired authentication credentials
403ForbiddenAuthenticated user lacks permission for this action or resource
404Not FoundRequested resource ID or route does not exist
409ConflictUnique constraint violation (e.g., email already registered)
422Unprocessable EntityValid JSON syntax, but field types/constraints failed validation
500Internal Server ErrorUnhandled server exception (never expose raw tracebacks!)
401 vs 403 and 400 vs 422

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:

python
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):

Python 3Try It Live: Mini REST Dispatcher & JSON Responses
Output

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

Check Your Understanding

Which HTTP status code should a POST /users endpoint return when it successfully creates a new user?

Check Your Understanding

Why is POST considered non-idempotent compared to GET or DELETE?