FastAPI flashcards
Fast, typed Python APIs with docs built in.
Beginner friendly, starts from zero
0
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
: intthat 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. Start from zero (12 cards): What an API is, how apps talk to servers, and the Python words FastAPI builds on.
- 2. Core basics (16 cards): Install, routes, parameters, bodies, errors, status codes and automatic docs.
- 3. Next steps (16 cards): Dependencies, routers, validation, response models, uploads, lifespan, CORS and tests.
- 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:GETreads,POSTcreates,PUTorPATCHchange,DELETEremoves. - 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
: intsays 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
@) linksGET /helloto the function below. The type hint makesnametext 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
pipinto a virtual environment, a private folder of packages, and Uvicorn, the server program, runs it on your computer at127.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 slashesAPIRouter(prefix="/admin", tags=["admin"])Group routesapp.include_router(r, dependencies=[Depends(auth)])Apply a dependency to a groupinclude_in_schema=FalseHide from docs@app.websocket("/ws")WebSocket route
Parameters
q: str | None = NoneOptional query valueAnnotated[int, Query(ge=1, le=100)]Bounded query valueAnnotated[str, Path(pattern=r"^[A-Z]{3}-\d+$")]Validated path valueAnnotated[Filter, Query()]Query params as a modelAnnotated[str, Header()]x_tokenreadsX-TokenAnnotated[str | None, Cookie()] = NoneCookie valuefile: UploadFileFile upload, streamedAnnotated[str, Form()]Form field
Dependencies
Annotated[DB, Depends(get_db)]Inject a resourceyield inside the dependencySetup and teardownDepends(fn, use_cache=False)Fresh value each useSecurity(scheme, scopes=["orders:read"])OAuth2 scopesapp.dependency_overrides[real] = fakeSwap in testsOAuth2PasswordBearer(tokenUrl="/token")Bearer token reader
Responses
-> OrderOutResponse model from return typeresponse_model_exclude_none=TrueDrop null fieldsraise HTTPException(404, "Not found")Error response@app.exception_handler(MyError)Map domain errorsStreamingResponse(gen(), media_type=...)Stream outputFileResponse(path, filename="a.pdf")Download a fileRedirectResponse(url, status_code=303)Redirect
CLI and URLs
fastapi dev main.pyDev server with reloadfastapi run main.py --workers 4Production serveruvicorn main:app --proxy-headersTrustX-Forwardedheaders/docs, /redoc, /openapi.jsonDocs and schemapip install "fastapi[standard]"Install with server and CLI