FastAPI Crash Course
๐ Fast API Crash Course: Building High-Performance Python Backends
Fast API is a modern, high-performance web framework for building APIs with Python. It enables the creation of powerful backends and microservices, focusing on speed and developer experience. This course covers the fundamentals, from architecture and routes to data models and documentation.
๐ What Fast API Offers
Fast API is built on top of the Starlette framework, an ASGI toolkit. ASGI (Asynchronous Server Gateway Interface) is the successor to WSGI (Web Server Gateway Interface), offering asynchronous capabilities to handle multiple requests concurrently, unlike WSGI's synchronous, one-at-a-time approach.
โจ Key Features of Fast API
Speed and Performance: Achieves performance comparable to Node.js due to Starlette's ASGI environment.
Automatic Data Validation & Serialization: Leverages Pydantic with Python type hints for robust data validation. This automatically strips out unexpected fields in requests and ensures data integrity.
Automatic Interactive Documentation: Includes Swagger UI (OpenAPI) and ReDoc out-of-the-box. Swagger UI provides interactive documentation that can also be used for testing API endpoints (GET, POST, PUT, DELETE) similar to Postman or cURL.
Dependency Injection System: Simplifies the management of components, database connections, and authentication by defining dependencies as functions, with Fast API handling their lifecycle.
Security Utilities: Built-in support for common security practices like OAuth 2 and JSON Web Tokens (JWT).
Developer Experience Focus: Features minimal boilerplate code, explicit and readable syntax, and extensive use of Python type hints for better code clarity and maintainability.
WebSockets and Streaming Support: Enables the development of real-time applications.
๐๏ธ High-Level Architecture Overview
A typical Fast API architecture involves a client (e.g., React, Vue, mobile app) making HTTP requests to a server running Fast API.
Client: Sends HTTP requests (e.g., GET, POST) to the server.
Entry Point: Often uses a proxy like Nginx as the entry point, potentially serving static files.
Fast API Server: Runs with an ASGI server (e.g.,
Uvicorn).Request Handling:
An HTTP request with a specific method and route (e.g.,
GET /api/v1/issues) interacts with the application's data layer (e.g., PostgreSQL, JSON document).Pydantic models (schemas) define the structure and validation rules for data, based on Python type hints.
The API fetches or manipulates data and returns a response.
Interactive Documentation: Swagger UI allows testing of all routes, including attaching form data or JSON data, facilitating development and debugging.
๐ ๏ธ Setting Up the Project
This section details the initial setup for a Fast API project, assuming basic Python experience.
๐ Virtual Environment Setup
It is crucial to use a virtual environment to localize project dependencies.
Create a project folder:
fast-api-issue-tracker(or any name).Open in IDE/Terminal: Navigate into the folder in your terminal and open it in your text editor (e.g., VS Code).
Create virtual environment:
python -m venv .venvThis creates a
.venvfolder containing the localized environment.Activate virtual environment:
Mac/Linux:
Windows:
.venv\Scripts\activate
Once activated, your terminal prompt will show
(.venv)or the folder name.
๐ฆ Installing Fast API
Install Fast API and its standard dependencies using pip.
Install Fast API with standard extras:
pip install "fastapi[standard]"The
standardextra includes essential packages like Pydantic and the Uvicorn ASGI server. This ensures dependencies are installed locally within the virtual environment.
๐ Creating the Entry Point (main.py)
The main.py file serves as the application's entry point, similar to server.js or app.js in Node.js/Express.
from fastapi import FastAPI
# Initialize Fast API
app = FastAPI()
# Example: Health Check Route
@app.get("/health")
def health_check():
return {"status": "OK"}
# To run the server:
# uvicorn main:app --reload
# Or using the Fast API dev wrapper:
# fastapi dev main.py๐งช Testing Routes with Swagger UI
Fast API automatically generates interactive documentation with Swagger UI.
Start the server:
fastapi dev main.pyThe server will typically run on
http://localhost:8000.Access Swagger UI: Open your browser and navigate to
http://localhost:8000/docs.Test the
healthendpoint:You will see a
GET /healthroute listed.Click "Try it out" and then "Execute" to send a request.
The response will show
{"status": "OK"}and a200status code.
๐ก Simple Route Examples
Fast API uses decorators to define routes and HTTP methods.
GET Request (Fetch all items)
items = [1, 2, 3]
@app.get("/items")
def get_items():
return itemsGET Request (Fetch single item by ID - Path Parameter)
@app.get("/items/{item_id}")
def get_item(item_id: int): # Type hint for path parameter
for item in items:
if item == item_id:
return item
raise HTTPException(status_code=404, detail="Item not found")POST Request (Create an item)
from fastapi import HTTPException, status
@app.post("/items", status_code=status.HTTP_201_CREATED)
def create_item(item: dict):
items.append(item)
return itemstatus_code=status.HTTP_201_CREATED: Sets the HTTP response status code to 201 for successful creation.Without Pydantic models, any JSON sent in the body will be accepted.
๐๏ธ Structuring Routes with APIRouter
For larger applications, it's best practice to organize routes into separate files using APIRouter.
Create
app/routes/issues.py:from fastapi import APIRouter router = APIRouter( prefix="/api/v1/issues", tags=["Issues"] ) @router.get("/") def get_issues(): return [] # Returns an empty list initiallyprefix: Adds a common prefix to all routes defined in this router (e.g.,/api/v1/issues).tags: Helps organize routes in the Swagger UI documentation.
Wire up the router in
main.py:from fastapi import FastAPI from app.routes.issues import router as issues_router # Import with alias app = FastAPI() # ... other middleware or routes ... app.include_router(issues_router) # Include the issues routerimport router as issues_router: Imports therouterobject and renames it toissues_routerto avoid naming conflicts.app.include_router(): Integrates the routes defined inissues_routerinto the main application.
๐พ Simple JSON File Storage
For this crash course, data will be stored in a simple JSON file instead of a database, keeping the focus on Fast API.
Create
app/storage.py:from pathlib import Path import json DATA_DIR = Path("data") # Directory for data files DATA_FILE = DATA_DIR / "issues.json" # Specific JSON file for issues def load_data(): if DATA_FILE.exists(): with open(DATA_FILE, "r") as f: content = f.read().strip() if content: return json.loads(content) return [] def save_data(data): DATA_DIR.mkdir(parents=True, exist_ok=True) # Create dir if not exists with open(DATA_FILE, "w") as f: json.dump(data, f, indent=2)load_data(): Reads data fromissues.json. If the file doesn't exist or is empty, it returns an empty list.save_data(data): Creates thedatadirectory if it doesn't exist, then writes the provideddatatoissues.jsonwith an indent of 2 for readability.
๐ Data Validation with Pydantic Schemas
Pydantic is used with Python type hints to define data schemas, enabling automatic validation and serialization.
Create
app/schemas.py:from enum import Enum from pydantic import BaseModel, Field from typing import Optional # Enums for strict values class IssueStatus(str, Enum): open = "open" in_progress = "in_progress" closed = "closed" class IssuePriority(str, Enum): low = "low" medium = "medium" high = "high" # Schema for creating an issue (request body) class IssueCreate(BaseModel): title: str = Field(min_length=3, max_length=100) description: str = Field(min_length=5, max_length=1000) priority: IssuePriority = IssuePriority.medium # Default value # Schema for updating an issue (optional fields) class IssueUpdate(BaseModel): title: Optional[str] = Field(default=None, max_length=100) description: Optional[str] = Field(default=None, max_length=1000) priority: Optional[IssuePriority] = None status: Optional[IssueStatus] = None # Schema for issue output/response class IssueOut(BaseModel): id: str title: str description: str priority: IssuePriority status: IssueStatusEnum: Defines a set of named constant values, ensuring strict data types forstatusandpriority.BaseModel: The base class for Pydantic models, allowing definition of data schemas.Field: Provides additional validation constraints likemin_length,max_length, and default values.Optional: From thetypingmodule, used to mark fields as optional for update operations, meaning they don't have to be present in the request body.
๐ CRUD Operations for Issues
This section implements the full CRUD (Create, Read, Update, Delete) functionality for issues using the APIRouter and Pydantic schemas.
Update
app/routes/issues.py:import uuid from fastapi import APIRouter, HTTPException, status from typing import List from app.schemas import IssueCreate, IssueOut, IssueUpdate, IssueStatus from app.storage import load_data, save_data router = APIRouter( prefix="/api/v1/issues", tags=["Issues"] ) # --- READ (All Issues) --- @router.get("/", response_model=List[IssueOut]) def get_issues(): """Retrieve all issues.""" issues = load_data() return issues # --- CREATE --- @router.post("/", response_model=IssueOut, status_code=status.HTTP_201_CREATED) def create_issue(payload: IssueCreate): """Create a new issue.""" issues = load_data() new_issue = { "id": str(uuid.uuid4()), "title": payload.title, "description": payload.description, "priority": payload.priority, "status": IssueStatus.open # Default status for new issues } issues.append(new_issue) save_data(issues) return new_issue # --- READ (Single Issue) --- @router.get("/{issue_id}", response_model=IssueOut) def get_issue(issue_id: str): """Retrieve a single issue by ID.""" issues = load_data() for issue in issues: if issue["id"] == issue_id: return issue raise HTTPException(status_code=404, detail="Issue not found") # --- UPDATE --- @router.put("/{issue_id}", response_model=IssueOut) def update_issue(issue_id: str, payload: IssueUpdate): """Update an existing issue.""" issues = load_data() for index, issue in enumerate(issues): if issue["id"] == issue_id: # Update fields only if they are provided (not None) if payload.title is not None: issues[index]["title"] = payload.title if payload.description is not None: issues[index]["description"] = payload.description if payload.priority is not None: issues[index]["priority"] = payload.priority if payload.status is not None: issues[index]["status"] = payload.status save_data(issues) return issues[index] raise HTTPException(status_code=404, detail="Issue not found") # --- DELETE --- @router.delete("/{issue_id}", status_code=status.HTTP_204_NO_CONTENT) def delete_issue(issue_id: str): """Delete an issue by ID.""" issues = load_data() initial_len = len(issues) issues = [issue for issue in issues if issue["id"] != issue_id] if len(issues) == initial_len: raise HTTPException(status_code=404, detail="Issue not found") save_data(issues) return # No content returned for 204response_model: Specifies the Pydantic schema that the route's response will conform to, ensuring proper serialization and documentation.uuid.uuid4(): Generates a unique ID for new issues.HTTPException: Used to raise custom HTTP errors with specific status codes and detail messages (e.g.,404 Not Found).status.HTTP_201_CREATED: Sets the status code for successful creation.status.HTTP_204_NO_CONTENT: Indicates a successful deletion where no content is returned.
โฑ๏ธ Custom Middleware for Request Timing
Middleware allows running code before or after each request, providing access to the request and response objects. This example demonstrates a custom timing middleware.
Create
app/middleware/timer.py:import time from fastapi import Request, Response async def timing_middleware(request: Request, call_next): """ Custom middleware to measure and report request processing time. Attaches 'X-Process-Time' header to the response. """ start_time = time.perf_counter() # High-resolution timer response = await call_next(request) # Call the next middleware/route handler process_time = time.perf_counter() - start_time response.headers["X-Process-Time"] = f"{process_time:.4f}s" # Add custom header return responsetime.perf_counter(): Provides a high-resolution timer to accurately measure elapsed time.await call_next(request): Passes the request to the next middleware or the route handler and waits for the response.response.headers["X-Process-Time"]: Adds a custom header to the HTTP response, containing the calculated processing time.
Wire up middleware in
main.py:from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from app.routes.issues import router as issues_router from app.middleware.timer import timing_middleware # Import custom middleware app = FastAPI() # Add custom timing middleware app.middleware("http")(timing_middleware) # ... include other routers ... app.include_router(issues_router)app.middleware("http")(timing_middleware): Registers thetiming_middlewareto run for all HTTP requests.
๐ Cross-Origin Resource Sharing (CORS) Middleware
CORS is a security feature that restricts web pages from making requests to a different domain than the one that served the web page. Fast API provides a built-in CORS middleware.
Add CORS middleware in
main.py:from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware # Import CORS middleware from app.routes.issues import router as issues_router from app.middleware.timer import timing_middleware app = FastAPI() app.middleware("http")(timing_middleware) # Add CORS middleware app.add_middleware( CORSMiddleware, allow_origins=["*"], # Allows all origins allow_credentials=True, allow_methods=["*"], # Allows all HTTP methods (GET, POST, PUT, DELETE, etc.) allow_headers=["*"], # Allows all headers ) app.include_router(issues_router)allow_origins=["*"]: Allows requests from any domain. For production, it's recommended to specify a list of allowed domains (e.g.,["http://localhost:3000", "https://yourfrontend.com"]).allow_methods=["*"]andallow_headers=["*"]: Allow all HTTP methods and headers, respectively.allow_credentials=True: Indicates that the browser should include credentials (like cookies or HTTP authentication) with the request.
โ๏ธ Deployment to Render.com
Render.com is a cloud platform that simplifies deployment, especially for those less familiar with DevOps.
Generate
requirements.txt:pip freeze > requirements.txtThis file lists all project dependencies, which Render uses to install necessary packages.
Push code to GitHub: Ensure your project code is in a GitHub repository.
Deploy on Render:
Log in to Render.com (you can use GitHub login).
Create a New Web Service.
Link your GitHub repository.
Build Command:
pip install -r requirements.txt(This is usually pre-filled).Start Command:
uvicorn main:app --host 0.0.0.0 --port $PORTmain:app: Refers to theappobject inmain.py.--host 0.0.0.0: Makes the application accessible from outside the container.--port $PORT: Uses the port provided by the hosting environment.
Choose a Free instance type.
Click Deploy Web Service.
Testing Deployment:
Once deployed, Render provides a public URL (e.g.,
fast-api-issue-tracker.onrender.com).Access the API endpoints (e.g.,
/api/v1/issues) and the Swagger documentation (/docs) on the live URL.Perform CRUD operations to verify functionality.
This completes the Fast API crash course, providing a foundational understanding of building high-performance APIs with Python.

Ask anything
We've read this whole study set, so questions about it get the best answers.