- Path Parameters: Identifying a specific resource.
- Query Parameters: Filtering or sorting resources.
- Request Bodies: Sending complex payloads (JSON) to create or update resources.
- Headers: Sending metadata (like auth credentials).
1. Request Data Processing Flow
FastAPI intercepts incoming HTTP requests, extracts parameters, validates their data types using Pydantic, and feeds them directly into your Python route function.2. Path Parameters
Path parameters are variables embedded directly inside the URL path. They are typically used to point to a specific, unique resource.Example: Fetching a Specific Employee
Let’s add an endpoint to retrieve a single employee using their uniqueemployee_id:
Key Takeaways
- Syntax: Define the variable in the path inside curly braces:
/employees/{employee_id}. - Type Safety: Annotate
employee_id: intin the function arguments. If a user requests/employees/abc, FastAPI immediately returns a422 Unprocessable Entityerror explaining thatemployee_idmust be an integer, saving you from writing manual type-checking code!
3. Query Parameters
Any function parameter that is not part of the path is automatically treated as a query parameter. Query parameters appear after the? in the URL (e.g., /employees?department=Product&role=Manager).
Example: Filtering Employees
Let’s add search and filtering functionality to the employee list endpoint:Key Takeaways
- Optional parameters: Use
str | None = Noneto denote an optional query parameter. - Default values: Provide a default value directly (e.g.,
limit: int = 10).
4. Request Bodies with Pydantic
When you need to send structured data to create or update a resource, you should use a Request Body via an HTTPPOST, PUT, or PATCH request. You define the shape of this body using a Pydantic Model.
Example: Creating (Onboarding) an Employee
First, define the schema, then declare the path operation parameter:Key Takeaways
- FastAPI automatically reads the body as JSON, validates it against
EmployeeCreate, and injects it as an object namedemployeeinto the function. - You can access the validation data using
.model_dump()to get a standard Python dictionary.
5. Headers & Metadata
You can read headers sent by clients (e.g., API keys, user-agent details, system configuration metrics) using theHeader class from FastAPI.
Example: Reading an API Key or Client User-Agent
[!NOTE] FastAPI automatically converts snake_case arguments (likex_api_key) to match kebab-case headers (likeX-API-Key) sent by the client.