TodayTools

FastAPI flashcards

Fast, typed Python APIs with docs built in.

Donate
Beginner friendly, starts from zero
Section
How to study
0
FastAPIStart from zero · 1 of 12

What is FastAPI, in one plain sentence?

FastAPI is a Python toolkit for building web APIs: programs that other apps call over the internet to fetch or save data.

You write Python functions; FastAPI puts them on the internet.

All topics

FastAPI at a glance

FastAPI turns ordinary Python functions into web APIs that apps can call.

Like a restaurant waiter: the app orders, the waiter (your API) takes it to the kitchen (your code) and brings back the dish (the data).

Words you will meet

Endpoint
One web address plus a method, like GET /orders
Request
What an app sends to your server
Response
What your server sends back
JSON
Data written as labels and values, readable by any app
Status code
A number that says how a request went, like 200 or 404
Type hint
A note like : int that says what kind of value is expected
Model
A Pydantic class listing the fields you expect
Query
The part of a web address after ?, like ?limit=20

The steps

  1. 1. Start from zero (12 cards): What an API is, how apps talk to servers, and the Python words FastAPI builds on.
  2. 2. Core basics (16 cards): Install, routes, parameters, bodies, errors, status codes and automatic docs.
  3. 3. Next steps (16 cards): Dependencies, routers, validation, response models, uploads, lifespan, CORS and tests.
  4. 4. Go deeper (16 cards): Security, async pitfalls, test overrides, deployment, streaming, WebSockets and idempotency.
All 12 cards in Start from zero
What is FastAPI, in one plain sentence?
FastAPI is a Python toolkit for building web APIs: programs that other apps call over the internet to fetch or save data.
What problem does FastAPI solve?
Without it, you write a lot of code by hand to check every value people send, turn answers into data apps can read, and write docs. FastAPI does all three from one short function.
Where do you already meet APIs in daily life?
A weather app asking a server for today's forecast, a food app showing where your order is, a bank app loading your balance. Each tap sends a request to an API and shows its answer.
What do client, server, request and response mean?
The client (a phone app or browser) sends a request, sometimes carrying data called the body. The server, a computer running your code, sends back a response.
What are a path, an endpoint and the HTTP methods?
A path is the part of a web address after the site name, like /orders, and the part after ? is the query. An endpoint (or route) is one path plus a method: GET reads, POST creates, PUT or PATCH change, DELETE removes.
What do status codes like 200, 404 and 422 tell the app?
A status code is a number on every response that says how it went: 200 OK, 201 created, 204 done with nothing to send, 404 not found, 422 the data sent was wrong.
What is JSON, the format FastAPI sends back?
JSON writes data as a label and a value, inside curly braces. Almost every app can read it, so it is the common language of APIs.
Which Python words will you need: function, dict and type hint?
A function is a named block of code that runs when called. A dict is Python's box of labels and values, which becomes JSON, and a type hint like : int says what kind of value a name should hold.
Your first tiny win: what does each line of this endpoint do?
The decorator line (starting with @) links GET /hello to the function below. The type hint makes name text read from the query, and the function returns a dict that FastAPI sends as JSON.
What are validation, Pydantic, a model and the docs page?
Validation means checking incoming data is the right kind before your code uses it. FastAPI does it with Pydantic, where a model is a class listing the fields you expect, and it builds a docs page (OpenAPI) where you can try every endpoint.
What do you need before you start?
Python 3.10 or newer, a terminal (the window for typing commands) and a text editor. You install FastAPI with pip into a virtual environment, a private folder of packages, and Uvicorn, the server program, runs it on your computer at 127.0.0.1:8000.
What will you be able to do after this topic?
Build a small API with read, create, update and delete endpoints, check every input, send clear errors and status codes, and share auto-made docs that others can try.
FastAPI cheatsheet

Routes

  • @app.get("/items/{item_id}") Path parameter
  • @app.post("/items", status_code=201) Create with status
  • {file_path:path} Path param that allows slashes
  • APIRouter(prefix="/admin", tags=["admin"]) Group routes
  • app.include_router(r, dependencies=[Depends(auth)]) Apply a dependency to a group
  • include_in_schema=False Hide from docs
  • @app.websocket("/ws") WebSocket route

Parameters

  • q: str | None = None Optional query value
  • Annotated[int, Query(ge=1, le=100)] Bounded query value
  • Annotated[str, Path(pattern=r"^[A-Z]{3}-\d+$")] Validated path value
  • Annotated[Filter, Query()] Query params as a model
  • Annotated[str, Header()] x_token reads X-Token
  • Annotated[str | None, Cookie()] = None Cookie value
  • file: UploadFile File upload, streamed
  • Annotated[str, Form()] Form field

Dependencies

  • Annotated[DB, Depends(get_db)] Inject a resource
  • yield inside the dependency Setup and teardown
  • Depends(fn, use_cache=False) Fresh value each use
  • Security(scheme, scopes=["orders:read"]) OAuth2 scopes
  • app.dependency_overrides[real] = fake Swap in tests
  • OAuth2PasswordBearer(tokenUrl="/token") Bearer token reader

Responses

  • -> OrderOut Response model from return type
  • response_model_exclude_none=True Drop null fields
  • raise HTTPException(404, "Not found") Error response
  • @app.exception_handler(MyError) Map domain errors
  • StreamingResponse(gen(), media_type=...) Stream output
  • FileResponse(path, filename="a.pdf") Download a file
  • RedirectResponse(url, status_code=303) Redirect

CLI and URLs

  • fastapi dev main.py Dev server with reload
  • fastapi run main.py --workers 4 Production server
  • uvicorn main:app --proxy-headers Trust X-Forwarded headers
  • /docs, /redoc, /openapi.json Docs and schema
  • pip install "fastapi[standard]" Install with server and CLI
Donate