Skip to content
Tutorials Center
My learning

Topics

Lesson 122 of 149 ยท Data and the Web

REST APIs with FastAPI

Learn FastAPI step by step. Build typed routes, path and query parameters, Pydantic request bodies, validation errors, dependencies and async endpoints in Python.

A REST API lets programs talk to each other over HTTP: a phone app asks for a list of books, a script posts a new order, a web page loads a user's profile. FastAPI is a modern Python framework for building these APIs. Its trick is that you describe your endpoints with ordinary type hints, and FastAPI uses those hints to read the request, check the data, convert it to the right types, reject bad input with a helpful message, and even generate interactive documentation for you.

If you built the project in JSON API with Flask, many ideas will look familiar: routes, JSON, status codes. The difference is how much FastAPI does for you. In Flask you write the validation code yourself; in FastAPI, a parameter declared as int simply cannot arrive as "seven". This lesson covers routes, path and query parameters, request bodies with Pydantic models, error handling, dependencies and async endpoints.

Running FastAPI here and at home

On your own computer you install FastAPI with its standard extras and start a development server:

Terminal
pip install "fastapi[standard]"
fastapi dev main.py

The server listens on http://127.0.0.1:8000. Open /docs in your browser for an interactive page where you can try every endpoint (generated from your code), or /redoc for a reading-friendly version. The raw description of your API lives at /openapi.json. In production you'd run it with an ASGI server such as Uvicorn behind a reverse proxy; see web development with Flask and Django for the general picture of how a Python app sits behind a web server.

The editors on this page can't open a network port, so the examples use a different route. FastAPI apps are ASGI applications, and the httpx library can call an ASGI app directly, in the same program, with no network. Your routes, validation and error handling run exactly as on a server. Each example installs the packages with micropip (see packages and pip) and uses a small call helper or an AsyncClient with top-level await. At home, you'd leave out the micropip lines and use fastapi.testclient.TestClient in your tests instead.

Sync or async endpoints? FastAPI runs a normal def endpoint in a thread pool, and an async def endpoint directly on the event loop. The browser editor cannot start threads, so every example here uses async def. On a real server both styles work; we'll come back to when to choose which.

Your first routes

An app is an instance of FastAPI. You attach functions to URLs with decorators named after the HTTP method: @app.get, @app.post, @app.put, @app.patch, @app.delete. Whatever the function returns, such as a dictionary or a list, is converted to JSON.

Python Hello, FastAPI

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Unknown URLs get a 404 with a JSON body automatically. Each request travels through the same stages, and FastAPI handles every one except your function:

sequenceDiagram
    participant C as Client
    participant F as FastAPI
    participant H as Your function
    C->>F: GET /items/7?limit=3
    F->>F: Match the route, read and validate parameters
    alt invalid input
        F-->>C: 422 with a list of problems
    else valid input
        F->>H: call read_item(item_id=7, limit=3)
        H-->>F: return value
        F-->>C: 200 with the value as JSON
    end

FastAPI validates the request before your function runs, so your code only ever sees data of the declared types.

Path and query parameters

Names in curly braces in the URL are path parameters. Any other function parameter that isn't part of the path becomes a query parameter, the ?key=value part of the URL. Type hints decide how each value is parsed, and a default value makes a query parameter optional:

Python Path and query parameters with validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at the two failing requests. You didn't write a single if or try, and still the API answers 422 Unprocessable Content with a machine-readable list of problems. Each entry's loc says where the bad value was (path, query, body, header), which makes it easy for a client to show the error next to the right form field. Also note that /items/7?limit=3 gives limit the integer 3, not the string "3".

Beyond the basics, the Query, Path, Header and Body helpers add constraints such as minimum length or allowed ranges. You'll see Query in the dependencies example below.

Request bodies with Pydantic

Real APIs receive structured data: a new user, an order with items. In FastAPI you describe the shape of that data as a Pydantic model, a class that inherits from BaseModel and lists fields with type hints (it feels much like a dataclass that validates itself). Declare the model as a parameter type, and FastAPI reads the JSON body, validates it, and gives you a ready model instance.

Models also describe responses. With response_model=, FastAPI filters what you return down to the fields of the model, so you can't leak a field such as a password hash by accident. The status_code argument sets the success code, and HTTPException returns an error response from anywhere in your code:

Python Models, status codes and errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A few things to notice:

  • The tags field was accepted on the way in (BookIn) but not sent back out (BookOut).
  • model_dump() turns a model into a plain dictionary.
  • The invalid body produced one problem per field, each with a loc that starts with "body".
  • Using separate input and output models is the standard way to keep what clients may send apart from what you reveal.

The list of HTTP verbs maps naturally onto actions on a resource: GET /books lists, POST /books creates, GET /books/1 reads one, PUT or PATCH /books/1 updates, DELETE /books/1 removes. Choose nouns for URLs and let the method be the verb. The same ideas are used in the Flask API project.

Dependencies, headers and constraints

Many endpoints share the same preparation: check a login, open a database session, read pagination settings. FastAPI's dependency injection lets you write that once as a function and ask for its result in the parameters of any endpoint, using Depends. A dependency can itself declare parameters (headers, query values, other dependencies), and they are validated the same way. If it raises HTTPException, the endpoint never runs.

The example also shows Annotated, the modern way to attach extra information to a type hint, with Query to constrain a parameter. The last part sends five requests at once to an endpoint that waits for 0.2 seconds, which shows what async is good for:

Python Dependencies, constraints and concurrency

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Header names are converted for you: the parameter x_api_key matches the header X-API-Key, because HTTP headers use hyphens and Python names can't. A missing header is a 422 (the request itself is malformed), while a wrong key is the 401 that your dependency raised. Dependencies compose: an endpoint that needs "the current user" would depend on a function that depends on the API key check, and so on.

async def or def?

Both are allowed on the same app:

  • Use async def when your function awaits asynchronous libraries: an async database driver, an HTTP client like httpx.AsyncClient, asyncio.sleep. While one request waits, the event loop serves others. Read asynchronous programming with asyncio first if await is new to you.
  • Use plain def when you call blocking code (requests, a normal database driver, heavy file reads). FastAPI runs those functions in a thread pool, so one slow call doesn't freeze every other request.
  • The one mistake to avoid is blocking inside async def: calling time.sleep() or a blocking database library there stalls the whole event loop and all users with it.

CPU-heavy work (image processing, large calculations) fits neither; push it to a background worker or process pool as described in the concurrency lesson.

Structuring a larger app

You don't keep everything in one file for long. These are the pieces you'll add as the project grows. They are read-only here because they involve several files or a real server:

Python
# routers/books.py
from fastapi import APIRouter

router = APIRouter(prefix="/books", tags=["books"])

@router.get("/")
async def list_books(): ...

# main.py
from contextlib import asynccontextmanager
from fastapi import FastAPI
from routers import books

@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.db = await open_database()      # runs once at startup
    yield
    await app.state.db.close()                # runs once at shutdown

app = FastAPI(lifespan=lifespan)
app.include_router(books.router)

An APIRouter groups related endpoints and is attached to the app with include_router. The lifespan function is an async context manager for start-up and shut-down work, such as opening a connection pool. For storage, FastAPI pairs naturally with SQLAlchemy: a dependency opens a session for each request and closes it afterwards.

For tests, create a TestClient(app) (it needs httpx), call client.get(...), and assert on response.status_code and response.json(), exactly as in the examples above. Since validation lives in the type hints, a handful of tests covering the happy path and one bad input per endpoint goes a long way (see testing).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A route is declared as @app.get('/users/{user_id}') with async def read_user(user_id: int). What happens for the request GET /users/abc?

    FastAPI validates the value against the int hint before calling your function. A failure gives a 422 response whose body says which part of the request was wrong.
  2. 2. What is the main reason to use a separate response model with response_model=?

    FastAPI filters the returned data through the response model, keeping only its fields. That prevents accidentally exposing things such as password hashes.
  3. 3. Where does a parameter end up if it is not part of the URL path and is a simple type like int or str?

    Parameters not found in the path and declared with simple types are query parameters (?name=value). Pydantic models are read from the body.
  4. 4. What is Depends(require_key) used for?

    A dependency is a function FastAPI calls for you. Its return value becomes the parameter value, and if it raises an HTTPException the endpoint is never run.
  5. 5. Which line is a problem inside an async def endpoint?

    time.sleep() blocks the whole event loop, so no other request can be served meanwhile. Use await asyncio.sleep(), or define the endpoint with plain def to run it in a thread.

Summary

  • FastAPI turns type-hinted Python functions into HTTP endpoints, validates input and documents the API automatically (/docs).
  • Parameters in the path are path parameters, other simple parameters are query parameters, and Pydantic models are read from the JSON body.
  • Invalid requests get a 422 response with a list of problems before your code runs; use HTTPException for your own errors such as 404 and 401.
  • response_model filters the output; separate input and output models keep private fields private.
  • Depends shares logic like authentication; Annotated with Query or Header adds constraints.
  • Use async def with async libraries and plain def with blocking ones; never block inside async def.
  • httpx with an ASGI transport (or TestClient) lets you call your app without a server, which is perfect for tests.

Next: Project: Rock, Paper, Scissors.