Understand the code
This page reads the main.py of the shop project from Generate and sends each endpoint good and bad requests. You learn how FastAPI reads query parameters, path parameters and a JSON request body, how it validates them and answers 422 when they are wrong, how a response model and a status code shape the answer, how HTTPException returns an error, and when to write async def.
How to read main.py
Read main.py from top to bottom. The first time the file uses a FastAPI idea, a comment of one or two lines explains it and ends with the link to the FastAPI tutorial page about it. Each idea is commented only once, so a later endpoint that does the same thing has no comment.
To follow along, start the server in the project folder with fastkit runserver and send the requests below from a second terminal. The items live in memory, so restart the server first if you already created items in /docs; otherwise your ids differ from the ones below, and you use the id that your POST returned. You can send the same requests from http://127.0.0.1:8000/docs with "Try it out".
The app and the models
A pydantic model is a class whose attributes declare the fields of a JSON object and their types. FastAPI uses it to read a request body, check it and convert it into a Python object. Field(...) adds limits: here a name of 1 to 100 characters and a price above 0.
app = FastAPI(title="shop")
# An argument typed with a pydantic model (`item: Item`) is the validated JSON body.
# https://fastapi.tiangolo.com/tutorial/body/
class Item(BaseModel):
name: str = Field(min_length=1, max_length=100)
price: float = Field(gt=0)
description: str | None = None
# The return type of an endpoint is its response model: it shapes the output.
# https://fastapi.tiangolo.com/tutorial/response-model/
class StoredItem(Item):
id: int
items: dict[int, StoredItem] = {}
StoredItem is an Item with an id: the client sends an Item, and the API answers with a StoredItem. items is a plain dictionary that keeps the items in memory, so they are gone when the server restarts.
Query parameters
A query parameter is a key=value pair after the ? in a URL, as in /?name=Ada. In FastAPI, an argument with a simple type such as str or int that is not part of the path is a query parameter by default; an argument whose type is a pydantic model is read from the request body instead, as the next section shows. Query(...) adds limits, and the default value ("World") makes the parameter optional.
@app.get("/")
async def read_root(
# A str, int or bool argument not in the path is a query parameter: /?name=Ada
# https://fastapi.tiangolo.com/tutorial/query-params/
name: Annotated[str, Query(min_length=1, max_length=50)] = "World",
) -> dict[str, str]:
return {"message": f"Hello, {name}! Welcome to {app.title}", "docs": "/docs"}
An empty name breaks the min_length=1 limit. FastAPI rejects the request before your function runs and answers 422 Unprocessable Entity. The body says where the problem is (loc: the name query parameter) and what is wrong (msg):
$ curl -s -i "http://127.0.0.1:8000/?name="
HTTP/1.1 422 Unprocessable Entity
...
{"detail":[{"type":"string_too_short","loc":["query","name"],"msg":"String should have at least 1 character","input":"","ctx":{"min_length":1}}]}
Request body and status codes
When an argument's type is a pydantic model, FastAPI reads it from the JSON body of the request. The return type, StoredItem, is the response model: FastAPI checks the returned object against it, sends only its fields, and documents it at /docs. status_code=status.HTTP_201_CREATED replaces the default 200 with 201 Created, the usual status when a request creates something.
# `status_code` sets the status of a successful response: 201 Created.
# https://fastapi.tiangolo.com/tutorial/response-status-code/
@app.post("/items", status_code=status.HTTP_201_CREATED)
async def create_item(item: Item) -> StoredItem:
stored = StoredItem(id=len(items) + 1, **item.model_dump())
items[stored.id] = stored
return stored
$ curl -s -i -X POST http://127.0.0.1:8000/items -H "Content-Type: application/json" -d '{"name": "Hammer", "price": 9.5}'
HTTP/1.1 201 Created
...
{"name":"Hammer","price":9.5,"description":null,"id":1}
The body left out description, so it is null (Python's None), the default in the model. A negative price breaks Field(gt=0), and the 422 body points at price in the body:
$ curl -s -i -X POST http://127.0.0.1:8000/items -H "Content-Type: application/json" -d '{"name": "Saw", "price": -1}'
HTTP/1.1 422 Unprocessable Entity
...
{"detail":[{"type":"greater_than","loc":["body","price"],"msg":"Input should be greater than 0","input":-1,"ctx":{"gt":0.0}}]}


Path parameters and errors
A path parameter is a part of the path itself, written {item_id} in the decorator. FastAPI passes it to the function argument of the same name and converts it to the declared type, int. When no item has that id, the function raises HTTPException: FastAPI stops the request there and answers with the status and the detail you gave it.
# `{item_id}` in the path arrives as an argument, converted to `int`.
# https://fastapi.tiangolo.com/tutorial/path-params/
@app.get("/items/{item_id}")
async def read_item(item_id: int) -> StoredItem:
if item_id not in items:
# HTTPException stops the request and answers with an error status.
# https://fastapi.tiangolo.com/tutorial/handling-errors/
raise HTTPException(status.HTTP_404_NOT_FOUND, detail="Item not found")
return items[item_id]
$ curl -s http://127.0.0.1:8000/items/1
{"name":"Hammer","price":9.5,"description":null,"id":1}
$ curl -s -i http://127.0.0.1:8000/items/99
HTTP/1.1 404 Not Found
...
{"detail":"Item not found"}
$ curl -s -i http://127.0.0.1:8000/items/abc
HTTP/1.1 422 Unprocessable Entity
...
{"detail":[{"type":"int_parsing","loc":["path","item_id"],"msg":"Input should be a valid integer, unable to parse string as an integer","input":"abc"}]}
abc is not an integer, so FastAPI answers 422 without calling read_item. You never have to convert or check item_id yourself.
async def or def
Every endpoint in main.py is an async def function. Inside async def you can await other asynchronous code, such as an async database driver or HTTP client, and the server handles other requests while one waits. These endpoints only read and write a dictionary, so they never wait. Use a plain def when an endpoint calls a library that blocks (one without await): FastAPI then runs it in a thread pool, so it does not hold up the other requests.
FastAPI documentation
- Query parameters
- Request body
- Response model
- Response status codes
- Path parameters
- Handling errors
- Concurrency and async / await
Next
Extend the app adds a /users resource, first by hand and then with a layered project and fastkit addroute.