Glossary
134 terms from Building APIs with FastAPI, in plain words, each with the chapter that teaches it.
#
- .env file
- A file of `NAME=value` lines that holds secrets such as `SECRET_KEY` outside your code. Keep it out of Git, and real environment variables override it.
A
- Alembic
- A database migration tool for SQLAlchemy and SQLModel that changes existing tables, such as adding a column, without losing data. It is what you reach for once `create_all`, which never alters existing tables, is no longer enough.
- Annotated
- A Python typing feature meaning 'this type, plus extra information'. Python ignores the extra part and FastAPI reads it, for example `Annotated[int, Query(ge=1)]` or `Annotated[Session, Depends(get_session)]`.
- API
- An API (application programming interface) is a service built for programs rather than people to use. A web API is one you reach over HTTP, like the Kettle & Crane API the shop and cafés call.
- API key
- A long secret string that a program, such as a café's ordering system, sends with each request to identify itself to an API. It is commonly sent in a header such as `X-API-Key`.
- APIKeyHeader
- A ready-made FastAPI dependency, from `fastapi.security`, that reads an API key from a named header. It answers 401 if the header is missing and adds an Authorize button to `/docs`.
- APIRouter
- A mini-app that holds a group of endpoints in their own file, with an optional `prefix` and `tags`. You attach it to the main app with `app.include_router`.
- app.dependency_overrides
- A dict on the FastAPI app that maps a dependency to a replacement. Tests use it to swap `get_session` for one that gives an in-memory test database.
- Argon2
- A deliberately slow, memory-hungry password hashing method that FastAPI's docs recommend. It is used through the pwdlib library.
- async def
- A way to write an endpoint that runs on the event loop and can `await` other work without holding up other requests. Never put blocking calls such as `time.sleep` or a database session inside one.
- asynccontextmanager
- A decorator from `contextlib` that turns an async generator into a context manager. FastAPI uses one for the lifespan function, which sets up before `yield` and cleans up after.
- asyncio
- Python's built-in library for running many `async` tasks concurrently on one event loop. Functions such as `asyncio.sleep` (pause without blocking) and `asyncio.gather` (run several awaitables at once) are part of it.
- Authentication / authorization
- Authentication finds out who is calling, and failing it gets a 401. Authorization decides what that caller may do, and failing it gets a 403.
- Authorization header
- The request header that carries a login token, written `Authorization: Bearer <token>`.
- Auto-reload
- A development feature that restarts the server each time you save a Python file, so your changes take effect at once. `fastapi dev` turns it on and `fastapi run` turns it off.
B
- Background task
- A function FastAPI runs after the response has been sent, such as emailing a confirmation without making the client wait. It runs inside the server process, so it is lost if the server stops.
- BackgroundTasks
- A FastAPI parameter type you add to an endpoint, which FastAPI fills in. You call `tasks.add_task(function, args...)` to schedule work after the reply.
- BaseModel
- The Pydantic class you inherit from to describe data. You write a type hint for each field, and the model validates and converts values when an object is created.
- Bearer token
- A token sent in the header `Authorization: Bearer <token>`, meaning 'whoever bears this token'. The login at `/token` returns one after a correct password.
- Blocking call
- Code that makes the program wait without letting anything else run, such as `time.sleep`, `requests.get`, `sqlite3` or a SQLModel session. Inside an `async def` endpoint it freezes the whole server, so use `def` for such code.
- Body
- The optional data part of a request or response, after the headers and a blank line. For Kettle & Crane's API it is usually JSON.
C
- Celery
- A task queue: a separate program that stores long-running or critical jobs and retries them if they fail. It is a sturdier alternative to FastAPI background tasks, which are lost if the server process stops.
- Client / server
- The client is the program that asks, such as curl or an online shop. The server is the program that waits for requests and answers them, which is the role a FastAPI app plays.
- commit
- The session call that saves all pending changes to the database together. Until you commit, added or changed objects aren't saved.
- conftest.py
- A file that pytest loads automatically, whose fixtures are shared with every test in its folder. It is the usual place for shared fixtures such as a test database session, a test client and an authentication header.
- Container
- A package holding your code, Python and every dependency, which runs the same anywhere. It is the usual way to ship an API to production.
- CORS
- CORS (cross-origin resource sharing) is how a server tells browsers that a web page from another origin may read its responses. FastAPI adds the `access-control-allow-origin` headers through `CORSMiddleware`.
- Counter
- A dict from the `collections` module that counts things and starts every count at 0. The orders router uses it to add up quantities per product, so two lines of 15 mugs become 30.
- CRUD
- Create, read, update, delete: the four basic jobs of any data store. The HTTP methods POST, GET, PUT or PATCH, and DELETE cover them.
- curl
- A command-line program that sends HTTP requests and prints the response. Options include `-i` for headers, `-X` for the method, `-H` for a header and `-d` for a body.
D
- Database URL
- A string naming the database to use, such as `sqlite:///kettle.db`. Switching to PostgreSQL mostly means changing this URL.
- Decimal
- Python's exact number type for money, which avoids the small errors floats can have. It is stored in a `Numeric` column and sent in JSON as a string such as `"55.00"`.
- Decorator
- A line starting with `@` above a function that changes how it is used. `@app.get("/")` registers the function as the handler for GET requests to `/`.
- default_factory
- A `Field` option that calls a function for every new object to produce its default. It makes each order get its own creation time, instead of one time worked out when the file loads.
- Dependency
- A function FastAPI runs before your endpoint, passing in its result. It takes its parameters from the request and can raise errors, such as a 404 for a missing product.
- Dependency injection
- A design where a function declares what it needs and something else provides it. In FastAPI an endpoint asks for `ProductDep` or `SessionDep` and the framework supplies it.
- Depends
- The FastAPI function that marks a parameter as coming from a dependency, as in `Depends(pagination)`. Pass the function itself, not a call to it.
- Development mode
- The mode `fastapi dev` runs in, with auto-reload and listening only on your own machine. It is not meant for real users.
E
- EmailStr
- A Pydantic type that accepts only text shaped like an email address. It checks the shape, not whether the mailbox exists.
- Endpoint
- A method plus a path, such as `GET /products`, handled by one function in your app. FastAPI's own docs call it a path operation.
- Engine
- The SQLModel/SQLAlchemy object that manages connections to the database. An app has one engine.
- Event loop
- The single line of work `asyncio` uses to juggle `async` code. If something blocks it, every request waits.
- Exception handler
- A function registered with `@app.exception_handler(SomeError)` that turns your own exception into a response. For example, `OutOfStock` becomes a 409 `JSONResponse`.
- extra="forbid"
- A Pydantic model setting that rejects unknown fields instead of silently ignoring them. It catches typos such as `"prise"`.
F
- fastapi dev
- The command that runs your app in development mode with auto-reload on 127.0.0.1:8000, for example `fastapi dev main.py`.
- fastapi run
- The command that runs your app for production. It turns reload off, listens on 0.0.0.0, and takes options like `--workers 4`.
- Field
- A function that adds rules or defaults to a model field, such as `Field(gt=0)` or `Field(min_length=3)`. SQLModel's version also takes column options like `primary_key` and `unique`.
- Fixture
- A pytest function that prepares something tests need, such as a fresh database session or a logged-in header. A test gets it by naming it as a parameter.
- Foreign key
- A column holding the ID of a row in another table, such as `OrderLine.order_id`. The database refuses a value that doesn't match an existing row.
- Form
- The `name=value` format HTML forms use to send data. The `/token` login endpoint expects its username and password as a form, not JSON.
H
- Happy path
- The case where everything goes right. Tests should check it, and the failure cases too.
- Hash
- A one-way scrambled version of a password that is safe to store. You can check a password against it but not reverse it.
- Header
- A `Name: value` line of extra information in a request or response, such as `content-type: application/json`.
- Health endpoint
- A simple endpoint such as `GET /health` that returns `{"status": "ok"}`. Hosting platforms call it to check the app is alive.
- Host addresses (127.0.0.1, 0.0.0.0)
- 127.0.0.1 is the numeric address behind `localhost`; `fastapi dev` listens only on it, so only your own computer can call the server. 0.0.0.0 means every network address of the machine; `fastapi run` listens on it so other computers can connect.
- HS256
- A JWT signing method (HMAC with SHA-256) that signs and verifies tokens using one shared secret key. Anyone holding that key can both create and check tokens.
- HTTP
- Hypertext Transfer Protocol, the rules for how web requests and responses are written. Browsers, curl and your API all use it.
- HTTP status codes
- A response's three-digit result: 2xx means success, 4xx a client mistake, 5xx a server bug. Common ones: 200 OK (success), 201 Created (after a POST), 204 No Content (after a DELETE), 307 Temporary Redirect (sent to the `location` header's URL, e.g. for a trailing slash), 401 Unauthorized (who are you?), 403 Forbidden (known, but not allowed), 404 Not Found (no such thing), 405 Method Not Allowed (path exists, wrong method), 409 Conflict (valid but clashes with stored data), 422 Unprocessable Content (data failed validation) and 500 Internal Server Error (a bug in your code).
- HTTPException
- A FastAPI exception you `raise` with a `status_code` and `detail`. FastAPI stops your function and sends the error as JSON.
- HTTPS
- HTTP encrypted for travel across a network. Logins must never be sent without it, and a reverse proxy usually provides it.
- httpx
- A Python HTTP library with an interface much like `requests`, supporting both sync and async use. It can call an API from Python, for example with `json=` to send a JSON body, and FastAPI's `TestClient` works like it.
I
- ID
- Short for identifier: a number that picks out one item, such as the 5 in `/products/5`. In a database table it is usually the primary key.
- In-memory database
- A SQLite database kept in RAM, made with the URL `sqlite://`, that vanishes when closed. Tests use it with `StaticPool`, which makes the engine reuse one connection so the database isn't recreated empty.
- Index
- A lookup structure that makes searching or filtering a column fast, such as products by category.
J
- JSON
- A text format for data made of objects, lists, strings and numbers, which web APIs use for bodies. FastAPI converts it to Python dicts and lists and back.
- JSONResponse
- A FastAPI class, from `fastapi.responses`, that builds a JSON response by hand from a status code and content. It is useful when you need full control of the response, such as inside an exception handler.
- JWT
- JSON Web Token, a signed string of three dot-separated parts that proves who a client is. Anyone can read it, but nobody can change it without the secret key.
L
- Lifespan
- A function FastAPI runs when the server starts and stops, with code before `yield` running at startup and code after it at shutdown. It is used for setup work such as creating database tables before the first request.
- localhost
- A name that always means 'this computer'. While you develop, the client and server both run on it.
M
- Method
- The verb of a request: GET reads, POST creates, PUT replaces, PATCH changes part, DELETE removes.
- Middleware
- Code that runs around every request and response. CORSMiddleware is the example, adding CORS headers.
- Migration
- A scripted change to existing database tables, made without losing data. `create_all` never alters existing tables, so real projects use a migration tool such as Alembic.
- model_dump
- The Pydantic method that turns a model into a dict. `exclude_none=True` leaves out fields that are `None`, which is how PATCH changes only what was sent; `model_validate` and `sqlmodel_update` copy data into table objects.
N
- Nested model
- A model whose field is another model or a list of them, such as a quote holding a list of lines. Every inner item is validated too, and an error's `loc` shows its position.
O
- OAuth2
- A widely used authorization standard. FastAPI supports its password flow: post a username and password as a form to `/token`, get a bearer token back.
- OpenAPI
- A standard, machine-readable description of every path, parameter and response of an API. FastAPI generates it at `/openapi.json`, and `/docs` is built from it.
- Origin
- A web page's scheme, host and port together, such as `http://localhost:5173`. Browsers compare origins to decide what a page may read.
- ORM
- An object-relational mapper: a library that maps database tables to classes and rows to objects, and writes the SQL for you. SQLModel is an example.
P
- Pagination
- Returning a long list a slice at a time using `offset` (how many items to skip) and `limit` (how many to return) query parameters. It keeps responses small and fast.
- Path
- The part of a URL that names the resource, such as `/products`. It is the 'to what' in a request like `GET /products`.
- Path (validation)
- The FastAPI function used inside `Annotated` to add rules to a path parameter, such as `Path(ge=1)`.
- Path parameter
- A value taken from the path, written `{name}` in the route, such as the 5 in `/products/5`. Its type hint makes FastAPI convert the text.
- pip
- Python's package installer. `pip install "fastapi[standard]"` downloads FastAPI and its extras into the active virtual environment.
- Port
- A numbered door on a computer that a server listens on. FastAPI uses 8000.
- PostgreSQL
- A database server suited to several workers or machines writing at once. It is the usual choice once SQLite's single-file limits start to matter in production.
- Preflight
- The `OPTIONS` request a browser sends before a request like a POST with JSON, to ask permission under CORS. The CORS middleware answers it.
- Primary key
- The column that uniquely identifies each row, here `id`. The database fills it in when a row is saved.
- pwdlib
- A Python password hashing library that supports Argon2. Its `hash` method makes a hash from a password and `verify` checks a password against a stored hash.
- Pydantic
- The library that checks and converts data against models. FastAPI uses it for request bodies, responses and settings.
- pydantic-settings
- A library that reads environment variables and a `.env` file into a validated Pydantic model. It keeps secrets such as `SECRET_KEY` out of the code.
- pytest
- A Python testing tool that finds test functions, runs them, and reports failures. It also provides fixtures for sharing setup between tests.
Q
- Query
- The FastAPI function used inside `Annotated` to add rules to a query parameter, such as `Query(ge=1, le=50)`.
- Query parameter
- A function parameter that isn't in the path, filled from the query string. It is optional if it has a default and is used to filter, sort or page.
- Query string
- The part of a URL after `?`, holding `name=value` pairs joined by `&`, such as `?category=merch&limit=5`.
R
- Rate limit
- A cap on how many requests a client may make in a given time. It is advised on `/token` so nobody can try thousands of passwords a minute.
- refresh
- The session call that reloads an object from the database after a commit, so values like `product.id` are filled in.
- Regular expression
- A pattern language for matching text. `Query(pattern="^(name|price)$")` accepts only the words name or price.
- Relationship
- An attribute that isn't a column but gives you linked rows of another table as objects, such as `order.lines` or `line.order`.
- Request / response
- A request is what a client sends: method, path, headers and an optional body. A response is what the server returns: status code, headers and a body.
- Required and optional parameters
- A parameter or model field with no default is required, and leaving it out gets a 422 `Field required`. Giving it a default, such as `limit: int = 10` or `stock: int = Field(default=0)`, makes it optional.
- Resource
- A thing the API manages, named by the path, such as products or orders.
- Response model
- The model, usually written as the return type hint, that controls what an endpoint sends back. FastAPI checks the result against it and sends only its fields, so hidden ones such as `stock` can't leak.
- REST
- The style where paths are nouns (usually plural) and methods are verbs, so there's no `/getProducts`. Most web APIs follow it.
- Reverse proxy
- A server in front of yours that handles HTTPS and passes requests on to Uvicorn. Nginx and Caddy are examples.
- Route order
- FastAPI tries paths in the order they are declared, so a fixed path like `/products/cheapest` must come before `/products/{product_id}`. Otherwise the parameter path matches first and gives a 422.
S
- Salt
- Random data mixed into a password before hashing, so identical passwords get different hashes.
- Same-origin policy
- The browser rule that stops a page from reading responses from another origin unless that server allows it through CORS.
- secrets.compare_digest
- A Python function that compares two strings in the same time however much they match. Using it instead of `==` stops attackers timing responses to guess a key one character at a time.
- select
- SQLModel's way to build a query, as in `select(Product).where(Product.price < 60)`. `session.exec(query).all()` runs it, `.first()` gives one row or None, and `session.get` fetches by primary key.
- Session
- One conversation with the database: you add and change objects, then commit to save them together. Each request gets its own through a `yield` dependency.
- Shell variable
- A value your terminal remembers under a name, such as `TOKEN=...`, which you then use as `$TOKEN` in later commands.
- Signature
- The last part of a JWT, made with your secret key, which proves nobody has changed the token.
- SKU
- A stock keeping unit, a short product code such as `ESP-5LB`. The API keeps SKUs unique.
- SQL injection
- An attack that sneaks SQL commands in through user input. SQLModel avoids it by sending values separately from the SQL, as long as you never build SQL strings yourself.
- SQLAlchemy
- The most widely used Python database toolkit, which SQLModel is built on.
- SQLite
- A database stored in a single file, convenient for development and small apps. Several processes writing the same file can cause `database is locked` errors, so it suits production poorly.
- SQLModel
- A library whose classes are both Pydantic models and database tables, built on SQLAlchemy and made by FastAPI's author.
- StringConstraints
- A Pydantic helper that holds rules for strings, such as a `pattern`. It is used with `Annotated` to name a reusable type like `Category`.
- Swagger UI
- The interactive documentation page FastAPI builds at `/docs`. You can try endpoints there, and the Authorize button handles logins.
T
- Table model
- A SQLModel class with `table=True`, which creates a database table. Unlike the other models, it does no validation, so never accept it directly from clients.
- Task queue
- A separate program that stores background jobs and retries them, such as Celery. It is the safer choice for long or critical jobs.
- TestClient
- A FastAPI client that calls your app directly inside a test, with no server or network. It works like httpx.
- Thread pool
- A set of worker threads kept ready. FastAPI runs `def` endpoints in one, so blocking code doesn't hold up other requests.
- Token
- A string a client gets by logging in and sends later to prove who it is, so it doesn't resend the password every time.
- Type alias
- A short name for a long type, such as `SessionDep` for `Annotated[Session, Depends(get_session)]`.
- Type hint
- A Python annotation giving a value's type, such as `product_id: int`. In FastAPI, type hints are instructions that decide how values are converted and checked.
U
V
- Validation
- Checking data against rules, converting where safe, so the text `"18"` becomes `18.0` and `"twelve"` is refused. Failures produce a 422 listing every problem.
- ValidationError
- The Pydantic exception raised when a model is built from bad data, listing every problem found.
- Virtual environment
- An isolated folder of installed Python packages for one project. Activate it before installing or running things.
W
- Worker
- One copy of your app running in its own process. `--workers 4` starts four so several CPU cores work at once, but each has its own memory.
- WWW-Authenticate
- A response header that a 401 response should carry, naming the authentication scheme the client must use, as the HTTP standard expects. For token logins its value is `WWW-Authenticate: Bearer`.
Y
- yield dependency
- A dependency written with `yield`: code before it runs before the endpoint and code after it runs once the response is done. It is used for database connections and sessions.