Request Bodies
To create a post, the client must send its title and content to the server. A request body carries this data from client to server.
We will send POST /posts, with title and content in a JSON request body.
{
"title": "A new post",
"content": "Let’s learn FastAPI"
}
Defining the Request Data
The server must check that the input has the required values and correct types. FastAPI uses Pydantic to validate request bodies.
Define a Pydantic model for a new post's title and content. Add this below the imports in main.py:
from pydantic import BaseModel
class PostCreateRequest(BaseModel):
title: str
content: str
As in our existing posts, title and content hold the title and body. Both are declared as str, so both must be strings.
The request model omits id. It is a primary key assigned by the system to distinguish posts. Clients provide the title and content, but do not choose the ID.
Allowing clients to choose IDs could create collisions with existing posts or simultaneous requests. The system assigns unique primary keys instead.
Receiving the Body
Add a handler for POST /posts. First, we will receive and return the input. Place this below the PostCreateRequest and app definitions in main.py:
@app.post("/posts", summary="Create a post") # ①
def create_post_handler(body: PostCreateRequest): # ②
return {"title": body.title, "content": body.content} # ③
- ① The decorator connects
POST /poststo this handler. -
② A Pydantic model annotation such as
body: PostCreateRequesttells FastAPI to read and validate the request JSON. After successful validation, it passes aPostCreateRequestobject tobody.For example, sending
{"title": "A new post", "content": "Let's learn FastAPI"}gives the handler an object equivalent to:body = PostCreateRequest(title="A new post", content="Let’s learn FastAPI")bodyis just the parameter name; you could call itpost_datainstead. -
③ Read
body.titleandbody.contentand return them in a dictionary.
Before calling the handler, FastAPI checks that the required title and content fields exist and match the model's types. Valid data becomes a PostCreateRequest instance ready for use. Invalid input produces 422.
Creating a Post
Now assign an ID on the server and add the post to posts. Update create_post_handler:
@app.post("/posts", summary="Create a post")
def create_post_handler(body: PostCreateRequest):
new_post = { # ①
"id": len(posts) + 1,
"title": body.title,
"content": body.content,
}
posts.append(new_post) # ②
return new_post # ③
- ①
new_postcontains the new ID, title, and content. Since this example starts at 1 and does not yet delete posts, the next ID is the number of posts plus 1. With two existing posts, it is3. - ②
posts.append(new_post)adds it to the end of the list. - ③ Return the new post, and FastAPI sends its ID, title, and content as JSON.
Trying It in Swagger UI
With the server running, open /docs. Expand POST /posts, click Try it out, paste the following JSON into the body field, and click Execute.
{
"title": "A new post",
"content": "Let’s learn FastAPI"
}
Response body shows your title and content along with the assigned ID. With two existing posts, it is 3. Run GET /posts to check that the list includes the new post.
Now remove the required title field and run POST /posts again:
{
"content": "Let’s learn FastAPI"
}
The status is 422. Check that detail contains loc: ["body", "title"], identifying the missing body field. Validation failed, so no post was added.
Restarting the Server
Stop the server with Ctrl+C, then restart it with fastapi dev. Run GET /posts in Swagger UI: only the original two posts remain. The new post is gone.
Our data currently lives in the in-memory posts list. It lasts only while the program runs. Restarting the server creates a fresh list from the two posts in the source code.
Real services use a database so posts survive restarts. We will learn that later. For now, remember that both manual restarts and automatic code reloads discard posts added while the server was running.
Check Your Understanding
Decide whether each statement is true or false.
- Clients must assign the primary key when creating a new resource.
- A handler parameter annotated with a Pydantic model lets FastAPI validate the request body.
- After validation, the handler can use the body as an instance of the declared model.
- FastAPI runs the handler before reporting a missing required body field.
- Data stored only in a process's memory is lost when that process restarts.
Answers and Explanations
- False — The server can assign primary keys to avoid collisions.
- True — The model declares the required fields and their expected types.
- True — FastAPI constructs and passes a validated model instance.
- False — Request validation occurs before the handler is called.
- True — Persistent storage, such as a database, is needed to retain data across restarts.