Your first FastAPI app
FastAPI builds APIs from ordinary Python functions with type hints. From those hints it validates incoming data, converts types, writes error messages and generates interactive documentation, all automatically. It's one of the fastest-growing Python frameworks.
Hello, FastAPI
app = FastAPI()creates the application.@app.get("/")is a path operation decorator: it registers the function below it forGETrequests to/.- Returning a dict (or list, or Pydantic model) sends it as JSON.
On your computer, save the app part as
main.pyand runfastapi dev main.py. Openhttp://127.0.0.1:8000/for the response andhttp://127.0.0.1:8000/docsfor interactive docs. In these editors, the "Try it" section at the bottom plays the role of the browser: it calls the app through httpx, exactly as FastAPI's own testing guide does.
Path parameters
Parts of the URL can be variables. Declare them in the path with {} and as function parameters with a type:
Look at /products/mug: because product_id is an int, FastAPI rejected the text with a 422 and a precise explanation. Your function never ran. And for /products/2, FastAPI converted the string "2" from the URL into the integer 2.
HTTPException stops the request and returns an error status with a detail message.
Query parameters
Function parameters that aren't in the path become query parameters (?key=value). Give them defaults to make them optional:
FastAPI understood sort_by_price=true as a boolean (it also accepts 1, yes and on), and turned max_price=cheap into a clear validation error.
Adding rules with Query and Path
ge means "greater than or equal", le "less than or equal". All three errors were reported at once.
async or not?
Path operations can be ordinary def functions or async def coroutines:
@app.get("/slow-report")
def report(): # blocking work (most database libraries): FastAPI runs it in a thread pool
return build_report()
@app.get("/weather")
async def weather(): # await-able work (httpx, async database drivers)
async with httpx.AsyncClient() as client:
r = await client.get("https://api.example.com/weather")
return r.json()Use async def when the code inside awaits things; otherwise plain def is fine and safe. Never call blocking functions (like time.sleep or requests.get) inside async def: they freeze every other request.
Automatic documentation
FastAPI generates an OpenAPI description of your API from the code, and serves it with two interactive UIs: Swagger UI at /docs and ReDoc at /redoc. The raw spec is at /openapi.json:
The docstring became the description, and the type hints became parameter types. The documentation can't drift from the code, because it is the code.
Practice
- Add
GET /products/{product_id}/price?currency=EURthat converts the price with a fixed rate (1 USD = 0.92 EUR), allowing onlyUSDandEUR(useLiteral["USD", "EUR"]). - Add a
limitquery parameter to/productsthat must be between 1 and 50. - Return a 404 with
detail="Category not found"whencategoryisn't one of the known ones.
1.In def get_item(item_id: int) for the path /items/{item_id}, what happens for /items/abc?
2.How do you make a query parameter optional?
3.Where does FastAPI serve interactive documentation by default?