1. Home
  2. Explore
  3. Computer Science
  4. FastAPI Crash Course

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

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.

  1. Client: Sends HTTP requests (e.g., GET, POST) to the server.

  2. Entry Point: Often uses a proxy like Nginx as the entry point, potentially serving static files.

  3. Fast API Server: Runs with an ASGI server (e.g., Uvicorn).

  4. 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.

  5. 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.

  1. Create a project folder: fast-api-issue-tracker (or any name).

  2. Open in IDE/Terminal: Navigate into the folder in your terminal and open it in your text editor (e.g., VS Code).

  3. Create virtual environment:

      python -m venv .venv

    This creates a .venv folder containing the localized environment.

  4. 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.

  1. Install Fast API with standard extras:

      pip install "fastapi[standard]"

    The standard extra 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.

  1. Start the server:

      fastapi dev main.py

    The server will typically run on http://localhost:8000.

  2. Access Swagger UI: Open your browser and navigate to http://localhost:8000/docs.

  3. Test the health endpoint:

    • You will see a GET /health route listed.

    • Click "Try it out" and then "Execute" to send a request.

    • The response will show {"status": "OK"} and a 200 status 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 items

GET 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 item
  • status_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.

  1. 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 initially
    • prefix: 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.

  2. 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 router
    • import router as issues_router: Imports the router object and renames it to issues_router to avoid naming conflicts.

    • app.include_router(): Integrates the routes defined in issues_router into 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.

  1. 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 from issues.json. If the file doesn't exist or is empty, it returns an empty list.

    • save_data(data): Creates the data directory if it doesn't exist, then writes the provided data to issues.json with 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.

  1. 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: IssueStatus
    • Enum: Defines a set of named constant values, ensuring strict data types for status and priority.

    • BaseModel: The base class for Pydantic models, allowing definition of data schemas.

    • Field: Provides additional validation constraints like min_length, max_length, and default values.

    • Optional: From the typing module, 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.

  1. 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 204
    • response_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.

  1. 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 response
    • time.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.

  2. 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 the timing_middleware to 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.

  1. 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=["*"] and allow_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.

  1. Generate requirements.txt:

      pip freeze > requirements.txt

    This file lists all project dependencies, which Render uses to install necessary packages.

  2. Push code to GitHub: Ensure your project code is in a GitHub repository.

  3. 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 $PORT

      • main:app: Refers to the app object in main.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.

  4. 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.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent