Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

FastAPI
  • FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
  • RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • What FastAPI Is: Starlette, Pydantic, uvicorn and What async def Really Gives You
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a FastAPI Blog: Every Folder and File an AI Agent Built, and What to Question
  • Swagger UI and OpenAPI in FastAPI: Reading the Contract Your Code Writes
  • POST, PUT and DELETE in FastAPI: Choosing 201, 200, 204 and 404 on the Server
  • Paging, Sorting and Filtering a REST API in FastAPI
  • API Versioning in FastAPI with an API-Version Header
  • Idempotent REST Methods, HATEOAS and the Maturity Model: Which Requests Are Safe to Repeat
  • A FastAPI REST API End to End: One App Visit, Seven Requests
  • The Book API in FastAPI: A Contract a React Client Can Rely On
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • FastAPI Request and Response Models with Pydantic: Design the JSON on Purpose
  • FastAPI Path, Query and Body Parameters: Reading a 422, response_model and Depends
  • Validation and Problem Details in FastAPI: From a 422 to One Error Shape for the Whole API
  • FastAPI with SQLAlchemy Models and Alembic Migrations: A Table from a Class, a Session per Request
  • From a List to a Database in FastAPI: Route, Service, Repository and the SQL SQLAlchemy Sends
  • Docker Compose: Run a FastAPI App and Postgres From One File
  • Docker Health Checks, Networks and Resource Limits: Up Is Not Enough
  • How a Request and a Login Flow Through a FastAPI Blog: Depends, bcrypt, a Signed Session Cookie and async def
  • Enterprise Integration for an AI App: One Adapter per Edge for SSO, the CRM, a Legacy CSV and Webhooks
  1. Blog
  2. /
  3. FastAPI
  4. /
  5. Fundamentals

The Book API in FastAPI: A Contract a React Client Can Rely On

The small FastAPI Book API behind a React client: spec at /v3/api-docs, a paged list with a page note, 400 Problem Details with a field errors map, and a one-time reshape of the OpenAPI spec.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Fundamentals

What you will learn

  • Serve the OpenAPI spec and Swagger UI at addresses you choose with openapi_url and docs_url
  • Return a paged list with a content array and a page note
  • Answer every error as a 400/404 Problem Details body with an errors map
  • Reshape the finished spec once by overriding app.openapi

Before you start

  • FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
  • FastAPI Request and Response Models with Pydantic

Picture a restaurant where the menu and the waiter stay the same, and a new cook starts in the kitchen. The guests order exactly as before. That is the job of this API: one small FastAPI app that answers the React client lectures in exactly the shape they expect, on port 8080.

It is worth a look on its own, because it shows four things a front end needs from any API: a spec at a known address, a paged list, errors in one predictable shape, and a spec the client's code generator can read. Every request and answer below comes from the project's saved run.

Three addresses on port 8080

AddressWhat it serves
/api/booksThe books, a page at a time
/v3/api-docsThe OpenAPI spec, as JSON
/swagger-ui/index.htmlThe Swagger UI page

Run it like any FastAPI app:

python -m venv .venv
.venv\Scripts\activate          # macOS / Linux: source .venv/bin/activate
pip install -r requirements.txt
uvicorn library.main:app --reload --port 8080

The books live in an in-memory SQLite database, so stopping the app forgets any changes.

FastAPI lets you choose the spec's address

By default FastAPI serves the spec at /openapi.json and Swagger UI at /docs (you met those in FastAPI Hello World). The React lectures look for /v3/api-docs, so main.py moves both (an excerpt):

app = FastAPI(
    title="Library API",
    version="1",
    openapi_url="/v3/api-docs",
    docs_url="/swagger-ui/index.html",
    openapi_tags=[{"name": "Books", "description": "Read, add, change and remove books"}],
    lifespan=lifespan,
)
app.include_router(books.router)
if os.environ.get("CORS_ORIGINS"):  # e.g. CORS_ORIGINS=http://localhost:5173
    app.add_middleware(CORSMiddleware, allow_origins=os.environ["CORS_ORIGINS"].split(","),
                       allow_methods=["*"], allow_headers=["*"], expose_headers=["Location"])
register_handlers(app)  # every error leaves the API as application/problem+json

openapi_url puts the spec where the client's generator looks, and docs_url moves Swagger UI. The CORS middleware is only switched on when CORS_ORIGINS is set; in development the Vite dev server forwards /api instead. The saved run confirms the spec:

GET /v3/api-docs  ->  200, Content-Type: application/json
{"openapi":"3.1.0","info":{"title":"Library API","version":"1"},"paths":{"/api/books":{"get":{"tags":["Books"],"summary":"List books, a page at a time","operationId":"list", ...

The format version, the title Library API, and three paths: /api/books, /api/books/{id} and /api/books/{id}/cover. The whole API, described at one address.

A page of books, and a note about the pages

The route, in library/routers/books.py (an excerpt):

@router.get(
    "",
    response_model=PagedModelBookResponse,
    summary="List books, a page at a time",
    operation_id="list",
)
def list_books(
    author: str | None = None,
    page: int = Query(0, ge=0),
    size: int = Query(5, ge=1, le=100),
    sort: list[str] = Query(["title"]),
    service: BookService = Depends(get_service),
):
    books, total = service.list_page(author, page, size, sort)
    return PagedModelBookResponse(
        content=books,
        page=PageMetadata(size=size, number=page, totalElements=total, totalPages=ceil(total / size)),
    )

The response models, in library/schemas.py (an excerpt):

class PageMetadata(BaseModel):
    # camelCase on purpose: the same JSON the Java version of this API sends
    size: int
    number: int
    totalElements: int
    totalPages: int


class PagedModelBookResponse(BaseModel):
    content: list[BookResponse]
    page: PageMetadata

The list takes page (counting from 0), size (5 by default) and sort, and answers with a content list plus a page note. The camelCase names are on purpose, so the JSON matches what the client was written for. Page 2 (number 1), five books, sorted by pages, biggest first:

GET /api/books?page=1&size=5&sort=pages,desc  ->  200
{"content":[{"id":9,"title":"The Silmarillion","author":"J.R.R. Tolkien","pages":365},
            {"id":1,"title":"The Hobbit","author":"J.R.R. Tolkien","pages":310},
            {"id":11,"title":"Mort","author":"Terry Pratchett","pages":272},
            {"id":5,"title":"Dune Messiah","author":"Frank Herbert","pages":256},
            {"id":4,"title":"Persuasion","author":"Jane Austen","pages":249}],
 "page":{"size":5,"number":1,"totalElements":12,"totalPages":3}}

Five books, page number 1, twelve books in all, three pages. The client reads the books and the paging note. ?size=50 returns all twelve at once, which is what the React lectures ask for.

A rejected book gets a 400 in one shape

FastAPI's default answer to a body that fails validation is a 422 with its own error list. This API answers 400 in Problem Details format (RFC 9457) instead, with an errors map a form can put under its fields. From library/errors.py (an excerpt):

def problem(request: Request, status: int, title: str, detail: str, **more) -> JSONResponse:
    """Problem Details (RFC 9457): one shape for every error."""
    body = {"detail": detail, "instance": request.url.path, "status": status, "title": title, **more}
    return JSONResponse(body, status_code=status, media_type="application/problem+json")


# what a failed rule says, in words a client can show
MESSAGES = {
    "missing": "{field} is required",
    "string_too_short": "{field} is required",
    "greater_than": "{field} must be more than 0",
}


def register_handlers(app: FastAPI) -> None:
    @app.exception_handler(ApiError)
    async def api_error(request: Request, error: ApiError):
        return problem(request, error.status, error.title, error.detail)

    @app.exception_handler(RequestValidationError)
    async def invalid(request: Request, error: RequestValidationError):
        errors = {}
        for item in error.errors():
            field = item["loc"][-1] if isinstance(item["loc"][-1], str) else "body"
            message = MESSAGES.get(item["type"], item["msg"]).format(field=field)
            errors.setdefault(field, message)  # the first message of each field
        return problem(request, 400, "Invalid book", "The book has invalid fields", errors=errors)

The request model says what counts as invalid. Text strips the spaces around a string before checking its length, so a title of only spaces counts as empty (library/schemas.py, an excerpt):

from typing import Annotated

from pydantic import BaseModel, ConfigDict, Field, StringConstraints

# text that must have at least one character once the spaces around it are cut off
Text = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1)]


class BookRequest(BaseModel):
    """What a client may send: no id, no shelf code, and rules the data must follow."""

    title: Text = Field(examples=["Matilda"])
    author: Text = Field(examples=["Roald Dahl"])
    pages: int = Field(gt=0, examples=[240])

A book with an empty title and zero pages:

POST /api/books  {"title": "", "author": "Roald Dahl", "pages": 0}
-> 400, Content-Type: application/problem+json
{"detail":"The book has invalid fields","instance":"/api/books","status":400,"title":"Invalid book",
 "errors":{"title":"title is required","pages":"pages must be more than 0"}}

The same problem() function answers errors the API raises on purpose, through the ApiError handler. A missing book:

GET /api/books/99  ->  404, Content-Type: application/problem+json
{"detail":"No book with id 99","instance":"/api/books/99","status":404,"title":"Book not found"}

Every error leaves the API in the same shape, so the client needs one way to read them.

Every error leaves through problem() RequestValidationError bad body: 400 ApiError (BookNotFound ...) 404, 413, 415, 400 problem() application/ problem+json detail, instance, status, title + errors map
Two handlers, one shape. The errors map is added for invalid bodies, one message per field.

Reshape the spec once

The client code was written against a spec with one pageable query parameter (holding page, size and sort), not three separate ones. FastAPI writes them as three. So main.py replaces app.openapi with a function that builds the spec once and rewrites it (an excerpt):

def contract():
    if app.openapi_schema is None:
        spec = FastAPI.openapi(app)
        schemas = spec["components"]["schemas"]
        schemas["Pageable"] = {
            "type": "object",
            "properties": {
                "page": {"type": "integer", "format": "int32", "minimum": 0},
                "size": {"type": "integer", "format": "int32", "minimum": 1},
                "sort": {"type": "array", "items": {"type": "string"}},
            },
        }
        listing = spec["paths"]["/api/books"]["get"]
        listing["parameters"] = [p for p in listing["parameters"] if p["name"] == "author"] + [
            {"name": "pageable", "in": "query", "required": True, "schema": {"$ref": "#/components/schemas/Pageable"}}
        ]
        for name in [n for n in schemas if n.startswith("Body_")]:
            schemas["UploadCoverBody"] = schemas.pop(name)
            text = json.dumps(spec).replace(f"#/components/schemas/{name}", "#/components/schemas/UploadCoverBody")
            spec.clear()
            spec.update(json.loads(text))
            schemas = spec["components"]["schemas"]
        # the API answers 400 (not 422) for a bad body: the 422 entries would be wrong
        for path in spec["paths"].values():
            for operation in path.values():
                operation["responses"].pop("422", None)
        schemas.pop("HTTPValidationError", None)
        schemas.pop("ValidationError", None)
    return app.openapi_schema


app.openapi = contract
  • page, size and sort become one parameter, pageable, with a Pageable schema.
  • The upload body FastAPI names Body_... is renamed UploadCoverBody.
  • The 422 entries are removed, because this API answers 400 for a bad body, so the client gets no types for an answer that never comes.

The requests on the wire do not change. It is still ?page=1&size=5&sort=pages,desc; only the spec reads differently, so the client's generated code compiles as written. Because the function stores its result in app.openapi_schema, the reshaping runs once.

Generated code may differ a little

When a tool generates a client from this spec, a few small things can differ from what the lectures show. That is expected, and nothing breaks:

  • Required fields. Pydantic declares id, title, author and pages as always present, so the generated type says id: number, not id?: number.
  • Order. Operations can appear in a different order inside a generated file.
  • Comments. FastAPI carries each model's docstring into the spec, so a comment can appear above each generated type.
  • Status codes. The success codes are the exact ones: 201 when a book is added, 204 when one is removed.

Tried against the React client

The client projects were run against this API (in temporary copies):

  • The client generated from /v3/api-docs builds with no type errors.
  • The React page shows 12 books, read from GET /api/books?size=50.
  • A title of only spaces gets 400, and title is required appears under the Title field.
  • A valid book (The Witches, Roald Dahl, 208) gets 201 with id 13, and the page shows 13 books.
  • Removing it gets 204 with an empty body, and the page is back to 12.

Quick recap

NeedHow the Book API does it
Spec where the client looksopenapi_url="/v3/api-docs"
Swagger UI at a known pagedocs_url="/swagger-ui/index.html"
Paged listcontent + page {size, number, totalElements, totalPages}
One error shapeapplication/problem+json, 400 with an errors map
Spec the client expectsapp.openapi = contract, reshaped once

The React side of this contract starts with Server State With TanStack Query.

Keep going in FastAPI · 16 of 26

Previous
A FastAPI REST API End to End: One App Visit, Seven Requests
Next post
A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

FastAPI Hello World: Routes, uvicorn and the Free Swagger Page

The smallest FastAPI app: two routes in main.py, started with uvicorn. Follow one request from the browser to the route table and back as JSON, see a 404, and try the routes on the free Swagger page at /docs.

RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes

An API is the waiter between your program and a server. REST gives each resource an address and uses the HTTP method for the action. Send GET, POST, PUT, PATCH and DELETE to a tiny local server with urllib, see why requests are stateless, and read 200, 201, 204, 400 and 404.

Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose

One small project lists two blog posts three times: as a Django view, a Flask route and a FastAPI endpoint. See each shape with its real output, what each framework includes, and a three-question way to choose.

One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask

The same blog built in Django, FastAPI and Flask, compared line by line: the list route, the Post model, the template loop, the project layout and the extras, with a ROSETTA map you can use to port a feature with AI.

On this page

  • Three addresses on port 8080
  • FastAPI lets you choose the spec's address
  • A page of books, and a note about the pages
  • A rejected book gets a 400 in one shape
  • Reshape the spec once
  • Generated code may differ a little
  • Tried against the React client
  • Quick recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.