REST APIs
suggest changeA REST API is an HTTP API organized around resources. Each resource (a book, a user, an order) has a URL, and you act on it with the standard HTTP methods. Requests and responses usually carry JSON.
GET /books list books (with filters and pagination)
POST /books create a book -> 201 Created + Location header
GET /books/42 read one book -> 200, or 404 if it doesn't exist
PUT /books/42 replace the whole book -> 200
PATCH /books/42 change some fields -> 200
DELETE /books/42 delete the book -> 204 No Content
The rules that make an API feel "RESTful":
- URLs name things, methods are verbs. Use
POST /books, notPOST /createBook. Collections are plural nouns. - Use the right method.
GETnever changes data.PUTandDELETEare idempotent: sending the same request twice has the same effect as sending it once, so clients can retry them safely.POSTis not idempotent. - Use status codes for the outcome.
200 OK,201 Created,204 No Content,400 Bad Request(malformed),401 Unauthorized(no or bad credentials),403 Forbidden(authenticated but not allowed),404 Not Found,409 Conflict,422 Unprocessable Content(valid JSON, invalid data),429 Too Many Requests,5xxfor server failures. Don't return200with{"error": ...}in the body. - Be stateless. Every request carries everything needed to process it, including credentials (usually an
Authorizationheader). The server doesn't remember a "current" state for the client between requests.
This article builds a small books API with FastAPI and Flask, then shows how to consume REST APIs from Python with httpx and requests: error handling, pagination, a typed client class, retries and tests.
All examples were run with Python 3.13, FastAPI 0.143, Pydantic 2.14, Flask 3.1, httpx 0.28 and requests 2.34.
Building an API with FastAPI
FastAPI is the most popular choice for new REST APIs in Python. You describe request and response bodies with Pydantic models and FastAPI validates input, serializes output and generates OpenAPI documentation from your type hints.
pip install fastapi uvicorn httpx2
uvicorn is the server. httpx2 is only needed for FastAPI's TestClient (recent Starlette versions moved from httpx to httpx2).
# books_api.py
from fastapi import FastAPI, HTTPException, Query, Response, status
from pydantic import BaseModel, Field
app = FastAPI(title="Books API")
class BookIn(BaseModel):
title: str = Field(min_length=1, max_length=200)
author: str = Field(min_length=1)
year: int = Field(ge=0, le=2100)
class BookPatch(BaseModel):
title: str | None = Field(default=None, min_length=1, max_length=200)
author: str | None = Field(default=None, min_length=1)
year: int | None = Field(default=None, ge=0, le=2100)
class Book(BookIn):
id: int
class BookPage(BaseModel):
items: list[Book]
total: int
limit: int
offset: int
books: dict[int, Book] = {}
next_id = 1
def get_or_404(book_id: int) -> Book:
book = books.get(book_id)
if book is None:
raise HTTPException(status_code=404, detail=f"book {book_id} not found")
return book
@app.get("/books")
def list_books(
author: str | None = None,
limit: int = Query(default=10, ge=1, le=100),
offset: int = Query(default=0, ge=0),
) -> BookPage:
found = [b for b in books.values() if author is None or b.author == author]
return BookPage(items=found[offset:offset + limit], total=len(found),
limit=limit, offset=offset)
@app.get("/books/{book_id}")
def get_book(book_id: int) -> Book:
return get_or_404(book_id)
@app.post("/books", status_code=status.HTTP_201_CREATED)
def create_book(data: BookIn, response: Response) -> Book:
global next_id
book = Book(id=next_id, **data.model_dump())
books[book.id] = book
next_id += 1
response.headers["Location"] = f"/books/{book.id}"
return book
@app.put("/books/{book_id}")
def replace_book(book_id: int, data: BookIn) -> Book:
get_or_404(book_id)
books[book_id] = Book(id=book_id, **data.model_dump())
return books[book_id]
@app.patch("/books/{book_id}")
def update_book(book_id: int, data: BookPatch) -> Book:
book = get_or_404(book_id)
changes = data.model_dump(exclude_unset=True)
books[book_id] = book.model_copy(update=changes)
return books[book_id]
@app.delete("/books/{book_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_book(book_id: int) -> None:
get_or_404(book_id)
del books[book_id]
How it maps to REST:
- The path parameter
book_id: intis parsed from/books/{book_id}. A non-integer gets a422automatically. - Function arguments that aren't in the path (
author,limit,offset) are query parameters.Query(ge=1, le=100)caps the page size so a client can't ask for a million rows. - An argument typed as a Pydantic model (
data: BookIn) is the JSON body. - The return type annotation (
-> Book) is the response model. FastAPI validates and serializes the return value through it, so extra fields never leak out. status_code=201on create and204on delete set the success status.HTTPExceptionproduces an error response.PUTtakes a fullBookIn(all fields required), whilePATCHtakesBookPatchwhere every field is optional.model_dump(exclude_unset=True)returns only the fields the client actually sent, so{"year": 1966}doesn't overwrite the title withNone.
The data lives in a dict to keep the example short. A real API would use a database; see Database connection pooling.
Run it with uvicorn books_api:app --reload --port 8000 and open http://127.0.0.1:8000/docs: FastAPI serves interactive Swagger UI built from the OpenAPI schema at /openapi.json.
Trying it with TestClient
TestClient calls the app in-process, without a running server. It's what you use in unit tests, and it's a convenient way to see what the API does:
from fastapi.testclient import TestClient
from books_api import app
client = TestClient(app)
r = client.post("/books", json={"title": "Dune", "author": "Frank Herbert", "year": 1965})
print(r.status_code, r.headers["location"], r.json())
client.post("/books", json={"title": "Emma", "author": "Jane Austen", "year": 1815})
client.post("/books", json={"title": "Persuasion", "author": "Jane Austen", "year": 1817})
r = client.get("/books", params={"author": "Jane Austen", "limit": 1})
print(r.status_code, r.json())
r = client.get("/books/1")
print(r.status_code, r.json())
r = client.patch("/books/1", json={"year": 1966})
print(r.status_code, r.json())
r = client.put("/books/1", json={"title": "Dune Messiah", "author": "Frank Herbert", "year": 1969})
print(r.status_code, r.json())
r = client.delete("/books/1")
print(r.status_code, repr(r.content))
r = client.get("/books/1")
print(r.status_code, r.json())
201 /books/1 {'title': 'Dune', 'author': 'Frank Herbert', 'year': 1965, 'id': 1}
200 {'items': [{'title': 'Emma', 'author': 'Jane Austen', 'year': 1815, 'id': 2}], 'total': 2, 'limit': 1, 'offset': 0}
200 {'title': 'Dune', 'author': 'Frank Herbert', 'year': 1965, 'id': 1}
200 {'title': 'Dune', 'author': 'Frank Herbert', 'year': 1966, 'id': 1}
200 {'title': 'Dune Messiah', 'author': 'Frank Herbert', 'year': 1969, 'id': 1}
204 b''
404 {'detail': 'book 1 not found'}
Validation errors
Invalid input never reaches your function. FastAPI answers with 422 and a list of every problem, each with a location (body, query, path) and a machine-readable type:
from fastapi.testclient import TestClient
from books_api import app
client = TestClient(app)
r = client.post("/books", json={"title": "", "year": "soon"})
print(r.status_code)
for err in r.json()["detail"]:
print(err["loc"], err["type"], "-", err["msg"])
r = client.get("/books/abc")
print(r.status_code, r.json()["detail"][0]["msg"])
r = client.delete("/books")
print(r.status_code, r.headers["allow"], r.json())
422
['body', 'title'] string_too_short - String should have at least 1 character
['body', 'author'] missing - Field required
['body', 'year'] int_parsing - Input should be a valid integer, unable to parse string as an integer
422 Input should be a valid integer, unable to parse string as an integer
405 GET {'detail': 'Method Not Allowed'}
A method the route doesn't support gets 405 Method Not Allowed with an Allow header listing the methods that work. See HTTP headers for more on headers in FastAPI.
Building the same API with Flask
Flask has no built-in validation or schema generation, but returning a dict from a view produces a JSON response, and the @app.get/@app.post shortcuts make REST routes concise. The important part is to return JSON errors too; by default Flask returns HTML error pages, which API clients can't parse.
# flask_api.py
from flask import Flask, abort, jsonify, request, url_for
app = Flask(__name__)
books = {}
next_id = 1
def validate(data, partial=False):
if not isinstance(data, dict):
abort(400, description="body must be a JSON object")
errors = {}
for field, kind in (("title", str), ("author", str), ("year", int)):
if field not in data:
if not partial:
errors[field] = "required"
elif not isinstance(data[field], kind) or isinstance(data[field], bool):
errors[field] = f"must be {kind.__name__}"
if errors:
response = jsonify(error="validation failed", fields=errors)
response.status_code = 422
abort(response)
return {k: data[k] for k in ("title", "author", "year") if k in data}
@app.errorhandler(400)
@app.errorhandler(404)
@app.errorhandler(405)
def json_error(e):
return jsonify(error=e.description), e.code
@app.get("/books")
def list_books():
limit = request.args.get("limit", 10, type=int)
offset = request.args.get("offset", 0, type=int)
items = list(books.values())
return {"items": items[offset:offset + limit], "total": len(items)}
@app.get("/books/<int:book_id>")
def get_book(book_id):
return books.get(book_id) or abort(404, description=f"book {book_id} not found")
@app.post("/books")
def create_book():
global next_id
book = {"id": next_id, **validate(request.get_json(silent=True))}
books[next_id] = book
next_id += 1
return book, 201, {"Location": url_for("get_book", book_id=book["id"])}
@app.patch("/books/<int:book_id>")
def update_book(book_id):
book = get_book(book_id)
book.update(validate(request.get_json(silent=True), partial=True))
return book
@app.delete("/books/<int:book_id>")
def delete_book(book_id):
get_book(book_id)
del books[book_id]
return "", 204
Flask's test client works like FastAPI's:
from flask_api import app
client = app.test_client()
r = client.post("/books", json={"title": "Dune", "author": "Frank Herbert", "year": 1965})
print(r.status_code, r.headers["Location"], r.get_json())
r = client.post("/books", json={"title": "Emma", "year": "1815"})
print(r.status_code, r.get_json())
r = client.post("/books", data="not json", content_type="application/json")
print(r.status_code, r.get_json())
r = client.patch("/books/1", json={"year": 1966})
print(r.status_code, r.get_json())
print(client.delete("/books/1").status_code)
r = client.get("/books/1")
print(r.status_code, r.get_json())
201 /books/1 {'author': 'Frank Herbert', 'id': 1, 'title': 'Dune', 'year': 1965}
422 {'error': 'validation failed', 'fields': {'author': 'required', 'year': 'must be int'}}
400 {'error': 'body must be a JSON object'}
200 {'author': 'Frank Herbert', 'id': 1, 'title': 'Dune', 'year': 1966}
204
404 {'error': 'book 1 not found'}
Notes:
request.get_json(silent=True)returnsNonefor a missing or malformed body instead of raising, sovalidatecan answer with a JSON400.- The
isinstance(..., bool)check matters:Trueis anintin Python, so without it{"year": true}would pass. abort()accepts a ready-made response, which is howvalidatereturns a422with a custom body.- Flask sorts JSON keys by default, which is why
authorcomes first.
For anything beyond a few endpoints, validate Flask input with Pydantic or marshmallow instead of hand-written checks. If browsers on another origin call the API, you also need CORS.
Consuming REST APIs with httpx
On the client side the two main libraries are requests (synchronous, ubiquitous) and httpx (similar API, plus async and HTTP/2). The examples below talk to the FastAPI server from above, started with uvicorn books_api:app --port 8000.
import httpx
BASE_URL = "http://127.0.0.1:8000"
with httpx.Client(base_url=BASE_URL, timeout=5.0) as client:
r = client.post("/books", json={"title": "Dune", "author": "Frank Herbert", "year": 1965})
r.raise_for_status()
book = r.json()
print(r.status_code, r.headers["location"], book)
r = client.get(f"/books/{book['id']}")
print(r.status_code, r.headers["content-type"], r.json()["title"])
r = client.get("/books", params={"author": "Frank Herbert"})
print(r.url)
print(r.json()["total"])
r = client.get("/books/999")
print(r.status_code, r.is_success, r.json())
try:
r.raise_for_status()
except httpx.HTTPStatusError as e:
print("error:", e.response.status_code, e.response.json()["detail"])
201 /books/1 {'title': 'Dune', 'author': 'Frank Herbert', 'year': 1965, 'id': 1}
200 application/json Dune
http://127.0.0.1:8000/books?author=Frank+Herbert
1
404 False {'detail': 'book 999 not found'}
error: 404 book 999 not found
The essentials:
- Reuse a
Client. It keeps a connection pool, so consecutive requests reuse the TCP and TLS connection.base_urllets you write relative paths. Creating a new client per request (or callinghttpx.get()in a loop) is much slower. json=serializes the body and setsContent-Type: application/json.params=builds the query string and handles URL-encoding (note the+for the space). Never build query strings with f-strings; see Parsing URLs.- An HTTP error status is not an exception. httpx and requests return the
404response normally. Callraise_for_status()or checkr.is_success/r.status_codeyourself. - Always set a timeout. httpx defaults to 5 seconds, but requests has no timeout by default and can hang forever on a dead server.
The same with requests
import requests
BASE_URL = "http://127.0.0.1:8000"
with requests.Session() as s:
s.headers["Accept"] = "application/json"
for title, year in [("Emma", 1815), ("Persuasion", 1817), ("Sense and Sensibility", 1811)]:
r = s.post(f"{BASE_URL}/books", json={"title": title, "author": "Jane Austen", "year": year},
timeout=5)
r.raise_for_status()
r = s.get(f"{BASE_URL}/books", params={"author": "Jane Austen", "limit": 2}, timeout=5)
print(r.status_code, r.ok)
page = r.json()
print(page["total"], [b["title"] for b in page["items"]])
r = s.patch(f"{BASE_URL}/books/2", json={"year": 1816}, timeout=5)
print(r.json())
r = s.delete(f"{BASE_URL}/books/1", timeout=5)
print(r.status_code, repr(r.text))
r = s.get(f"{BASE_URL}/books/1", timeout=5)
try:
r.raise_for_status()
except requests.HTTPError as e:
print(e)
200 True
3 ['Emma', 'Persuasion']
{'title': 'Emma', 'author': 'Jane Austen', 'year': 1816, 'id': 2}
204 ''
404 Client Error: Not Found for url: http://127.0.0.1:8000/books/1
requests.Session is the equivalent of httpx.Client: connection reuse plus shared headers. requests has no base_url, so you join URLs yourself. A 204 response has an empty body; calling r.json() on it raises an exception. More requests features are covered in Sessions, Authentication and Python Requests Post.
Pagination
List endpoints return one page at a time. A generator hides the paging from the caller. The event hook prints each request so you can see the pages being fetched:
from collections.abc import Iterator
import httpx
BASE_URL = "http://127.0.0.1:8000"
def iter_books(client: httpx.Client, page_size: int = 2, **filters) -> Iterator[dict]:
offset = 0
while True:
r = client.get("/books", params={**filters, "limit": page_size, "offset": offset})
r.raise_for_status()
page = r.json()
yield from page["items"]
offset += page_size
if offset >= page["total"]:
break
def log_request(request: httpx.Request) -> None:
print("->", request.method, request.url.path, request.url.query.decode())
with httpx.Client(base_url=BASE_URL, timeout=5.0,
event_hooks={"request": [log_request]}) as client:
for book in iter_books(client, author="Jane Austen"):
print(book["id"], book["title"], book["year"])
-> GET /books author=Jane+Austen&limit=2&offset=0
2 Emma 1816
3 Persuasion 1817
-> GET /books author=Jane+Austen&limit=2&offset=2
4 Sense and Sensibility 1811
Pages are only fetched as the loop consumes them, so break-ing early saves requests. APIs paginate in different ways and the generator is where you adapt to them:
- offset/limit (as here): simple, but rows can be skipped or repeated if data changes between pages.
- cursor: the response contains an opaque
next_cursoryou pass back. Stable under inserts and fast on large tables. Loop until the cursor isnull. - Link header: GitHub-style
Link: <...?page=3>; rel="next". httpx and requests parse it intor.links["next"]["url"].
A typed client class
Scattering client.get(...) and r.json()["..."] through an application spreads knowledge of URLs and error formats everywhere. Wrap the API in a small class that returns Pydantic models and raises meaningful exceptions:
# bookclient.py
import httpx
from pydantic import BaseModel, TypeAdapter
class Book(BaseModel):
id: int
title: str
author: str
year: int
class NotFound(Exception):
pass
class APIError(Exception):
def __init__(self, status: int, detail):
super().__init__(f"HTTP {status}: {detail}")
self.status = status
self.detail = detail
class BooksClient:
def __init__(self, base_url: str, token: str | None = None,
transport: httpx.BaseTransport | None = None):
headers = {"Accept": "application/json", "User-Agent": "books-client/1.0"}
if token:
headers["Authorization"] = f"Bearer {token}"
self._http = httpx.Client(base_url=base_url, headers=headers,
timeout=httpx.Timeout(10.0, connect=3.0),
transport=transport)
def __enter__(self):
return self
def __exit__(self, *exc):
self._http.close()
def _request(self, method: str, path: str, **kwargs) -> httpx.Response:
r = self._http.request(method, path, **kwargs)
if r.status_code == 404:
raise NotFound(path)
if r.is_error:
try:
detail = r.json().get("detail", r.text)
except ValueError:
detail = r.text
raise APIError(r.status_code, detail)
return r
def get(self, book_id: int) -> Book:
return Book.model_validate_json(self._request("GET", f"/books/{book_id}").content)
def search(self, author: str, limit: int = 10) -> list[Book]:
r = self._request("GET", "/books", params={"author": author, "limit": limit})
return TypeAdapter(list[Book]).validate_python(r.json()["items"])
def create(self, title: str, author: str, year: int) -> Book:
r = self._request("POST", "/books", json={"title": title, "author": author, "year": year})
return Book.model_validate_json(r.content)
def delete(self, book_id: int) -> None:
self._request("DELETE", f"/books/{book_id}")
from bookclient import APIError, BooksClient, NotFound
with BooksClient("http://127.0.0.1:8000") as api:
book = api.create("Middlemarch", "George Eliot", 1871)
print(book)
print(book.title, book.year + 1)
print(api.search("George Eliot"))
api.delete(book.id)
try:
api.get(book.id)
except NotFound as e:
print("not found:", e)
try:
api.create("Bad", "Nobody", 99999)
except APIError as e:
print(e.status, e.detail[0]["msg"])
id=5 title='Middlemarch' author='George Eliot' year=1871
Middlemarch 1872
[Book(id=5, title='Middlemarch', author='George Eliot', year=1871)]
not found: /books/5
422 Input should be less than or equal to 2100
Benefits of this shape:
- Callers get attributes with types (
book.year + 1) instead of dicts, and a changed or broken response fails loudly at the boundary with a PydanticValidationErrorrather than as aKeyErrordeep in your code. - Authentication,
User-Agent, timeouts and error mapping live in one place. Here the token is sent as a bearer token; OAuth and JWT explain where such tokens come from. - The
transportargument makes the class testable without a server (shown below).
Retries and rate limits
Networks fail and servers answer 429 Too Many Requests or 503 Service Unavailable under load. Retry those, but only when it's safe: retry idempotent methods freely, and don't automatically retry a POST after a connection error, because the server may have already created the resource. Respect the Retry-After header when the server sends it, and otherwise back off exponentially with random jitter so many clients don't retry in lockstep.
import random
import time
import httpx
RETRY_STATUSES = {429, 502, 503, 504}
IDEMPOTENT = {"GET", "HEAD", "PUT", "DELETE", "OPTIONS"}
def request_with_retries(client: httpx.Client, method: str, url: str,
attempts: int = 4, base_delay: float = 0.5, **kwargs) -> httpx.Response:
for attempt in range(1, attempts + 1):
try:
r = client.request(method, url, **kwargs)
except httpx.TransportError as e:
if attempt == attempts or method not in IDEMPOTENT:
raise
print(f"attempt {attempt}: {type(e).__name__}")
else:
if r.status_code not in RETRY_STATUSES or attempt == attempts:
return r
print(f"attempt {attempt}: HTTP {r.status_code}")
retry_after = r.headers.get("retry-after")
if retry_after and retry_after.isdigit():
time.sleep(min(int(retry_after), 30))
continue
# exponential backoff with jitter: ~0.5s, 1s, 2s, ...
time.sleep(base_delay * 2 ** (attempt - 1) * random.uniform(0.5, 1.5))
raise AssertionError("unreachable")
# a fake server that fails twice and then succeeds
calls = 0
def flaky(request: httpx.Request) -> httpx.Response:
global calls
calls += 1
if calls == 1:
return httpx.Response(503)
if calls == 2:
return httpx.Response(429, headers={"Retry-After": "1"})
return httpx.Response(200, json={"id": 1, "title": "Dune"})
with httpx.Client(base_url="https://api.example.com",
transport=httpx.MockTransport(flaky)) as client:
start = time.monotonic()
r = request_with_retries(client, "GET", "/books/1", base_delay=0.1)
print(r.status_code, r.json(), f"after {calls} calls, {time.monotonic() - start:.1f}s")
attempt 1: HTTP 503
attempt 2: HTTP 429
200 {'id': 1, 'title': 'Dune'} after 3 calls, 1.1s
httpx.MockTransport takes a function that turns a request into a response, which lets us simulate a flaky server. Retry-After can also be an HTTP date; HTTP headers shows how to parse it. Instead of writing the loop yourself you can use the tenacity library, or with requests mount an HTTPAdapter(max_retries=urllib3.Retry(...)), which handles status codes, backoff and Retry-After for you.
To make POST safely retryable, many APIs (Stripe, for example) accept an Idempotency-Key header: the client generates a UUID per logical operation and sends the same key on every retry, and the server returns the stored result instead of creating a duplicate.
Concurrent requests with AsyncClient
When you need many independent resources, httpx.AsyncClient fetches them concurrently over a shared connection pool:
import asyncio
import httpx
BASE_URL = "http://127.0.0.1:8000"
async def main():
async with httpx.AsyncClient(base_url=BASE_URL, timeout=5.0) as client:
responses = await asyncio.gather(*(client.get(f"/books/{i}") for i in range(1, 6)))
for r in responses:
print(r.request.url.path, r.status_code,
r.json().get("title") if r.is_success else r.json()["detail"])
asyncio.run(main())
/books/1 404 book 1 not found
/books/2 200 Emma
/books/3 200 Persuasion
/books/4 200 Sense and Sensibility
/books/5 404 book 5 not found
gather returns results in the order of the arguments, not the order they finished. Against a public API, limit concurrency with an asyncio.Semaphore (or httpx.Limits(max_connections=...)) so you don't trigger rate limiting. See Cancellation and timeouts for bounding the total time of a batch.
Testing API clients
Tests shouldn't depend on a real server. Pass a MockTransport into the client and assert both on what the client sends and on how it handles responses:
# test_bookclient.py
import json
import httpx
import pytest
from bookclient import APIError, BooksClient, NotFound
def handler(request: httpx.Request) -> httpx.Response:
assert request.headers["authorization"] == "Bearer secret"
if request.method == "GET" and request.url.path == "/books/1":
return httpx.Response(200, json={"id": 1, "title": "Dune",
"author": "Frank Herbert", "year": 1965})
if request.method == "POST" and request.url.path == "/books":
body = json.loads(request.content)
if body["year"] > 2100:
return httpx.Response(422, json={"detail": "year too large"})
return httpx.Response(201, json={"id": 7, **body})
return httpx.Response(404, json={"detail": "not found"})
@pytest.fixture
def api():
with BooksClient("https://api.test", token="secret",
transport=httpx.MockTransport(handler)) as client:
yield client
def test_get(api):
book = api.get(1)
assert book.title == "Dune" and book.year == 1965
def test_create(api):
assert api.create("Emma", "Jane Austen", 1815).id == 7
def test_not_found(api):
with pytest.raises(NotFound):
api.get(2)
def test_validation_error(api):
with pytest.raises(APIError) as exc:
api.create("Bad", "Nobody", 99999)
assert exc.value.status == 422
$ python -m pytest -q test_bookclient.py
.... [100%]
4 passed in 0.29s
For server-side tests use TestClient (FastAPI) or app.test_client() (Flask) as shown earlier. For requests-based code, the responses library plays the role of MockTransport. More on pytest in Testing with py.test.
Design tips
- Consistent error format. Pick one JSON shape for all errors (FastAPI's
{"detail": ...}, or the standardapplication/problem+jsonfrom RFC 9457 withtype,title,status,detail) and use it everywhere, including 404 and 500. - Return the created resource from
POSTwith201and aLocationheader, so clients don't need a second request. - Version the API (
/v1/books, or a header) before the first external client depends on it. Adding fields is backwards compatible; renaming or removing them is not. - Validate everything at the boundary, cap page sizes, and never pass raw input into SQL; see Application security.
- Use
ETag/If-None-Matchfor cacheableGETs andIf-MatchonPUT/PATCHto prevent lost updates when two clients edit the same resource. - Dates as ISO 8601 strings in UTC (
"2026-10-17T12:00:00Z"), money as strings or integer cents, IDs as strings if they may exceed 2^53 (JavaScript clients lose precision on larger integers).
Summary
- REST APIs model resources as URLs and use HTTP methods and status codes for operations and outcomes.
- FastAPI turns type hints and Pydantic models into validation, serialization and OpenAPI docs. Flask works too, but you must validate input and return JSON errors yourself.
- On the client, reuse an
httpx.Clientorrequests.Session, always set timeouts, and check status codes withraise_for_status(). - Wrap APIs in a typed client class, iterate pages with a generator, retry only idempotent requests with backoff, and test with
MockTransport.