FastAPI: The Fastest Python Web Framework
FastAPI is a modern Python framework for building APIs. Auto-generated docs, type validation, async support — it is as fast as Node.js and Go frameworks while being pure Python.
Why FastAPI
- Performance — on par with Node.js and Go
- Auto docs — Swagger UI and ReDoc generated automatically
- Type safety — Pydantic validation built-in
- Async — native async/await support
- Standards — OpenAPI and JSON Schema compliant
The Free API
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
in_stock: bool = True
@app.get("/")
def root():
return {"message": "Hello World"}
@app.post("/items/")
def create_item(item: Item):
return {"item": item, "total": item.price * 1.1}
@app.get("/items/{item_id}")
def get_item(item_id: int, q: str = None):
return {"item_id": item_id, "query": q}
pip install fastapi uvicorn
uvicorn main:app --reload
# Docs at http://localhost:8000/docs
# API at http://localhost:8000/openapi.json
Authentication
from fastapi import Depends, HTTPException
from fastapi.security import HTTPBearer
security = HTTPBearer()
@app.get("/protected")
def protected(token = Depends(security)):
if token.credentials != "secret":
raise HTTPException(401)
return {"data": "secret stuff"}
Database with SQLAlchemy
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
engine = create_engine("sqlite:///./app.db")
@app.get("/users/{user_id}")
def get_user(user_id: int):
with Session(engine) as session:
user = session.get(User, user_id)
return user
WebSocket
@app.websocket("/ws")
async def websocket_endpoint(websocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Echo: {data}")
Real-World Use Case
A data team needed an API for their ML model. FastAPI: 50 lines of code, auto-generated Swagger docs, Pydantic validation, async inference. From Jupyter notebook to production API in one afternoon. Handles 10K requests/sec.
Quick Start
pip install "fastapi[standard]"
fastapi dev main.py
Resources
Need data for your APIs? Check out my scraping tools on Apify or email spinov001@gmail.com for custom solutions.
Top comments (0)