FastAPI Request Bodies: Build a Small Local API
Create a local FastAPI endpoint with a Pydantic request model, try valid and invalid JSON, and separate validation from storage and permissions.
By Velloreth
A first API should make one thing easy to understand: what enters the endpoint and what comes back. FastAPI can read a JSON request body into a Pydantic model, validate its fields, and expose an interactive interface for trying the endpoint locally.
This guide builds a reading-task endpoint. It does not save tasks, create user accounts, or call an AI service. That smaller scope lets you see request validation without confusing it with a complete application.
Why this topic is timely
FastAPI appears in the 2026 Stack Overflow technology survey’s web-framework usage table. That supports its relevance to current developer learning; it does not establish a search-volume estimate or make it the best framework for every project. The official tutorial provides the source of truth for request-body behavior.
Before starting, understand the difference between a client and server. The client sends a request; the endpoint receives it. The HTTP status guide and REST design guide provide useful background if those terms are unfamiliar.
Create an isolated local project
Use Python 3.10 or newer for the type syntax below. Create and activate a virtual environment using your shell’s normal command, then install the development extras:
python -m venv .venv
For a typical macOS or Linux shell, activate with source .venv/bin/activate. PowerShell commonly uses .venv\Scripts\Activate.ps1. Respect any managed-machine policy. With the environment active, run:
python -m pip install "fastapi[standard]" "pydantic>=2,<3"
This installation is for a disposable practice folder. For a real project, record dependencies and versions in its normal dependency files. Avoid installing unrelated tutorial packages into a working application’s environment.
Define a request model and endpoint
Save the following as main.py:
from fastapi import FastAPI
from pydantic import BaseModel, Field
app = FastAPI()
class ReadingTask(BaseModel):
title: str = Field(min_length=1)
minutes: int = Field(ge=1, le=180)
completed: bool = False
@app.post("/tasks/")
def create_task(task: ReadingTask):
return {"task": task.model_dump(), "saved": False}
title and minutes have no defaults, so they are required. completed has a default, so the client may omit it. The range is an example rule for this practice app. It is not a framework requirement.
The function parameter tells FastAPI to read the request body using that model. model_dump() produces a dictionary suitable for this response. The explicit saved: False avoids implying that an echo endpoint has persisted anything.
Run and explore the local API
Start development mode:
fastapi dev main.py
Use the local address printed by the command. The default development setup exposes interactive documentation at http://127.0.0.1:8000/docs. Open it in your own browser, expand the POST /tasks/ operation, and use its try-out control.
Submit this JSON:
{
"title": "Read the API tutorial",
"minutes": 25
}
The response should echo the task, include completed: false, and say it was not saved. Those details are more useful than merely seeing a successful status. They confirm that the model default and response shape match the code you wrote.
If the port is already occupied, inspect the terminal and use the server’s supported port option. Do not kill an unknown process just to free a tutorial port. Stop the development server with the terminal’s normal interrupt when finished.
Try invalid requests deliberately
Change minutes to zero. Then remove title. These requests should fail validation before the endpoint function processes a valid task. FastAPI’s default request-validation response identifies the problem location and returns a client error, commonly status 422.
Next, send malformed JSON. This is a different failure from valid JSON containing an invalid task. Keep that distinction in the user interface: a syntax problem is not the same as a value outside an allowed range.
Pydantic can convert some compatible values, such as certain numeric strings, rather than rejecting all type differences. If strict input types are required, configure and test that policy deliberately. Do not promise strictness just because the model uses Python annotations.
Separate validation from application responsibilities
The endpoint has no database. Restarting it does not retrieve tasks because no retrieval or storage code exists. Adding a list in memory would still not be durable storage. A real task service needs a persistence design, identifiers, and a defined lifecycle.
It also has no authentication or permission checks. A request can match the schema perfectly and still be unauthorized. The API authentication guide explains that separate layer. Never use a client-supplied field such as is_admin as proof of authority.
Avoid returning or logging private request bodies without a reason. A tutorial payload contains harmless reading text; a real payload might contain personal information. Debugging practices should change with that sensitivity rather than copying every request into logs.
A small test plan before adding features
Write down the expected outcomes for a complete valid request, an omitted defaulted field, a missing required field, zero minutes, and malformed JSON. Test the response body as well as the status. If you later add storage, add a separate test that proves data can actually be read back.
Keep the first endpoint small until you can explain each line. Then decide on the next requirement: persistence, list retrieval, or authentication. Adding all three at once makes it harder to tell whether a failure comes from validation, routing, or the database.
Troubleshoot the first request
If the browser cannot connect, first confirm that the server process is still running and read the address printed in its terminal. If the interactive documentation opens but the operation fails, inspect the response body rather than reinstalling packages. A validation error usually points to a submitted field; an import error in the terminal points to code or environment setup.
Keep the terminal and browser open together while learning. Change one thing at a time, save the file, and confirm which version of the endpoint is running. If you accidentally started two servers, stop the practice processes you recognize and restart one clean session. Do not interpret a stale browser response as evidence that a code change had no effect.
Sources and limits
Checked October 26, 2026. Request-body behavior follows the official FastAPI tutorial. Current-use context comes from the 2026 Stack Overflow technology data. This is a local learning exercise, not a deployment or production-security recipe.