Taking JSON In: Your First Request Body

A POST route takes the JSON a request sends in its body through a small Pydantic model, a class that names each field and its type, then turns it into a dictionary with model_dump(), gives the new item the next id, and answers 201 with it.

Apprentice · FastAPI · REST API · Updated

By

After this lesson you can

  • Take a JSON request body with a small Pydantic model, and turn it into a dictionary with model_dump()
  • Add an item with a POST route that gives it the next id and answers 201 with the new item

Key takeaways

  • Data for a new item travels in the request's body as JSON, not in the address, so it can be long and hold any characters.
  • A Pydantic model is a class based on BaseModel whose type-hinted lines name the fields the JSON must have.
  • A route parameter whose type is a model tells FastAPI to read the body, check it against the model, and hand the route a ready object.
  • model_dump() turns the model into a dictionary, so the route can add an id and save it like the rest of the data.
  • A body with a missing field or a value of the wrong type gets a 422 that names the field, before the route runs.

Every sign-up form, new post and checkout sends data to an API: a name and an email, a post's text, the items in a cart. That data doesn't fit in the address. It travels in the request's body, and the API has to read it, check it and save it. This lesson shows the first, small version of that in FastAPI; Module 2 builds on it.

The example is the Rolling Dice café: a regular has donated a game, Dragon's Picnic, and staff want to add it to the shelf from the app.

Where does the new game go?

The new game has a title, the smallest and largest group it's made for, and how long it takes. Query parameters could carry all four: POST /games?title=Dragon's Picnic&min_players=3&max_players=5&minutes=60. That address is long, the spaces in the title have to be written in a special code to travel in an address, and addresses are saved in server logs, where anything in them can be read later.

A request has another place for data: its body, the part after the address and headers, usually JSON (HTTP in Plain Words: Requests and Responses showed its place in a request). The new game is sent like this:

{"title": "Dragon's Picnic", "min_players": 3, "max_players": 5, "minutes": 60}

The route needs to know which fields to expect and what type each one is.

A model says what JSON to expect

Pydantic is the library FastAPI uses to describe data, installed with FastAPI. You describe a body with a class based on BaseModel (read "a class NewGame, based on BaseModel"; Classes: Blueprints for Your Own Things covers classes). Each line in the class is a field name with a type hint. A class like this is called a model:

from pydantic import BaseModel


class NewGame(BaseModel):
    title: str
    min_players: int
    max_players: int
    minutes: int


new_game = NewGame(title="Dragon's Picnic", min_players=3, max_players=5, minutes=60)
print(new_game.title)
print(new_game.minutes + 15)
print(new_game.model_dump())
Dragon's Picnic
75
{'title': "Dragon's Picnic", 'min_players': 3, 'max_players': 5, 'minutes': 60}

A model's fields are read with a dot, like new_game.title, and model_dump() (read "model dump") turns the whole model into a plain dictionary. In a route, FastAPI makes the model from the request's JSON for you.

A POST route that adds the game

Adding to a list is a POST request to the list's own address, POST /games. The route takes a parameter whose type is the model, and that's how FastAPI knows to read the body:

@app.post("/games", status_code=201)
def add_game(new_game: NewGame):
    game = {"id": len(GAMES) + 1, **new_game.model_dump(), "available": True}
    GAMES.append(game)
    return game

The new game needs what the café's other games have: an id and available. The shelf has three games, so len(GAMES) + 1 gives 4. **new_game.model_dump() (the ** is read "unpack") copies the model's four fields into the new dictionary, between the id and available, which starts as True for a game that has arrived. The route saves the game with append and returns it, with 201 Created, as When It Isn't There: HTTPException and 404 showed for a route that creates:

{"id":4,"title":"Dragon's Picnic","min_players":3,"max_players":5,"minutes":60,"available":true}

Dragon's Picnic now shows up in GET /games too. It lives in the GAMES list, so it lasts until the server restarts; Module 3 keeps data in a database.

len(GAMES) + 1 works while games are only ever added. Once games can be removed, two games could get the same id, and Module 3's database hands out ids itself.

Try it on the docs page

Open http://127.0.0.1:8000/docs, click POST /games, then Try it out. FastAPI has filled the Request body box with an example built from the model. Replace it with Dragon's Picnic's JSON and click Execute:

FastAPI's docs page with POST /games opened and Try it out on: the Request body box holds Dragon's Picnic's JSON, and the response below is code 201 with the new game, id 4, available true

Now try a body that leaves out minutes. The answer is 422, before your route runs, and the body names the missing field:

{"detail":[{"type":"missing","loc":["body","minutes"],"msg":"Field required","input":{"title":"Night Train","min_players":5,"max_players":10}}]}

"minutes": "forty" gets a 422 too, with Input should be a valid integer. Fields the model doesn't name are dropped: a body that also sends "available": false still gets "available": true, because the route, not the request, decides that. Request Models with Pydantic, in Module 2, goes much further.

Check yourself

2 questions to try on the lesson page.

So what

A small model turns a request's JSON into a checked Python object before your route runs, so the route only has to do its real job: add the new item and say so with a 201.

Key terms

Related