Skip to main content
Components Web Framework

FastAPI

Core Stack

Modern, fast web framework for building APIs with Python

Version
0.104.1
Last Updated
2024-01-15
Difficulty
Intermediate
Reading Time
2 min

FastAPI

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints.

Key Features

  • High Performance: Very high performance, on par with NodeJS and Go (thanks to Starlette and Pydantic)
  • Fast to Code: Increase the speed to develop features by about 200% to 300%
  • Fewer Bugs: Reduce about 40% of human (developer) induced errors
  • Intuitive: Great editor support. Completion everywhere. Less time debugging
  • Easy: Designed to be easy to use and learn. Less time reading docs
  • Short: Minimize code duplication. Multiple features from each parameter declaration
  • Robust: Get production-ready code. With automatic interactive documentation

Installation

1
pip install fastapi uvicorn

Quick Start

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}

Run the server:

1
uvicorn main:app --reload

Use Cases

  • REST APIs: Perfect for building RESTful web services
  • Microservices: Lightweight and fast for microservice architectures
  • Real-time Applications: Built-in WebSocket support
  • ML Model Serving: Excellent for serving machine learning models

Best Practices

  1. Use Type Hints: Always use Python type hints for better validation and documentation
  2. Dependency Injection: Leverage FastAPI’s dependency injection system
  3. Async/Await: Use async functions for I/O operations
  4. Pydantic Models: Use Pydantic models for request/response validation
  5. Error Handling: Implement proper error handling with HTTP exceptions

Common Patterns

Request/Response Models

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float
    is_offer: bool = False

@app.post("/items/")
def create_item(item: Item):
    return item

Database Integration

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
from sqlalchemy.orm import Session
from . import crud, models, schemas
from .database import SessionLocal, engine

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@app.get("/users/{user_id}", response_model=schemas.User)
def read_user(user_id: int, db: Session = Depends(get_db)):
    db_user = crud.get_user(db, user_id=user_id)
    if db_user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return db_user

Resources

Alternatives

Flask

Lightweight WSGI web application framework

Key Strengths:
• Simple and minimalist design
• Large ecosystem of extensions
Best For:
• Simple web applications
• Prototyping
Beginner

Django

High-level Python web framework

Key Strengths:
• Batteries-included approach
• Built-in admin interface
Best For:
• Full-stack web applications
• Content management systems
Advanced

Starlette

Lightweight ASGI framework/toolkit

Key Strengths:
• High performance
• ASGI native
Best For:
• High-performance APIs
• Microservices
Intermediate

Quick Decision Guide

Choose FastAPI for the recommended stack with proven patterns and comprehensive support.
Choose Flask if you need simple web applications or similar specialized requirements.
Choose Django if you need full-stack web applications or similar specialized requirements.
Choose Starlette if you need high-performance apis or similar specialized requirements.