REST APIs

suggest change

A 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":

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

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:

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:

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:

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

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents