REST Architecture
REST (Representational State Transfer) is a set of architectural constraints for designing network APIs: resources identified by URLs, operations expressed with HTTP verbs, stateless requests, and standard status codes. FastAPI maps these concepts directly onto route decorators.
Resources and URLs
A resource is a noun (user, order, product) and lives at a URL. Collections are plural, single items include an identifier:
- GET /users - list users
- GET /users/42 - read one user
- POST /users - create a user
- PATCH /users/42 - partial update
- DELETE /users/42 - delete
HTTP Verbs in FastAPI
from fastapi import FastAPI, status
app = FastAPI()
@app.get("/users")
def list_users():
return []
@app.post("/users", status_code=status.HTTP_201_CREATED)
def create_user(name: str):
return {"name": name}
@app.get("/users/{user_id}")
def read_user(user_id: int):
return {"user_id": user_id}
@app.patch("/users/{user_id}")
def update_user(user_id: int, name: str | None = None):
return {"user_id": user_id, "name": name}
@app.delete("/users/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_user(user_id: int):
return None
Status Codes
| Code | Meaning | Typical use |
|---|---|---|
| 200 | OK | successful read/update |
| 201 | Created | POST created a resource |
| 204 | No Content | successful DELETE, empty body |
| 400 | Bad Request | malformed request |
| 404 | Not Found | resource does not exist |
| 422 | Unprocessable Entity | FastAPI validation failure |
| 500 | Internal Server Error | unexpected exception |
Conventions That Matter
- Use nouns, not verbs, in URLs: /orders, not /getOrders.
- Use query parameters for filtering and pagination: /orders?status=open&page=2.
- Return consistent JSON shapes: same field names, same error format everywhere.
- Keep requests stateless: each request carries everything needed (e.g., an auth token).
Summary
REST design in FastAPI means mapping HTTP verbs to route decorators (get, post, put, patch, delete), organizing URLs around noun resources with identifiers, and using the standard status code vocabulary. Follow the conventions and FastAPI handles the mechanical side while you focus on the domain.