FastAPI Architecture
FastAPI is not built from scratch — it combines Python language features, Starlette’s web layer, and Pydantic’s data layer into a single cohesive API framework.Setup and Installation
1
Create a virtual environment and activate it
2
Install FastAPI and Uvicorn
3
Create main.py with your first app
4
Run the server
Routing
A route maps an HTTP method + URL path to a Python function. The general pattern is:Common Routes
Path Parameters
Path parameters are embedded directly inside the URL path and identify a specific resource.101 from the URL and converts it to the int type automatically. If the value can’t be converted (e.g., /students/abc), FastAPI returns a 422 error without ever calling your function.
Query Parameters
Any function parameter that is not part of the path is automatically treated as a query parameter — the key-value pairs after? in the URL.
str | None = None to make a parameter optional:
Request Bodies
Use a Pydantic model to receive JSON data inPOST, PUT, and PATCH requests.
Student schema, creates a Student object, and passes it into your function. Access field values with student.name, student.age, etc.
Response Models
Declare the response structure usingresponse_model to control what gets sent back to the client:
StudentResponse, even if the returned dictionary contains more fields.
HTTP Status Codes
Set the correct success status code using thestatus_code parameter and constants from fastapi.status:
Data Validation
FastAPI provides three validators for different parameter sources:Field() — Request Body Validation
Use Field() inside Pydantic models. The recommended Pydantic v2 style uses Annotated:
Query() — Query Parameter Validation
Path() — Path Parameter Validation
Common Validation Options
EmailStr requires the email-validator package. Install it with pip install email-validator.REST API Design Conventions
Follow these naming conventions to keep your API clean and consistent:
Quick Rules