Installation and First App
Install FastAPI and uvicorn (ASGI server) and run your first API in minutes.
Python
# pip install fastapi uvicorn
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def root():
return {"message": "Hello from FastAPI!"}
@app.get("/items/{item_id}")
def get_item(item_id: int, q: str | None = None):
return {"item_id": item_id, "query": q}
# Run:
# uvicorn main:app --reload
# Visit: http://127.0.0.1:8000/docs β Auto Swagger UI!βΆ Output
{"message": "Hello from FastAPI!"}
{"item_id": 42, "query": null}Pydantic Models β Request/Response Validation
Use Pydantic models to define and validate request bodies automatically.
Python
from fastapi import FastAPI
from pydantic import BaseModel, EmailStr
from typing import Optional
app = FastAPI()
class User(BaseModel):
name: str
email: str
age: int
bio: Optional[str] = None
@app.post("/users/", response_model=User)
def create_user(user: User):
# user is already validated and typed
return user
# FastAPI auto-validates: wrong type = 422 error
# POST /users/ with {"name":"Alice","email":"a@b.com","age":30}βΆ Output
{"name":"Alice","email":"a@b.com","age":30,"bio":null}Dependency Injection
FastAPI's dependency injection system handles auth, DB connections, and shared logic.
Python
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import HTTPBearer
app = FastAPI()
security = HTTPBearer()
def get_current_user(token = Depends(security)):
if token.credentials != "secret-token":
raise HTTPException(status_code=401, detail="Invalid")
return {"user": "alice"}
@app.get("/protected")
def protected_route(user = Depends(get_current_user)):
return {"message": f"Welcome {user['user']}"}Ad β 336Γ280
Async Support
FastAPI supports both sync and async endpoints natively.
Python
import asyncio
from fastapi import FastAPI
import httpx
app = FastAPI()
@app.get("/async-data")
async def get_data():
async with httpx.AsyncClient() as client:
response = await client.get("https://api.github.com")
return response.json()Tip
Use async functions for I/O-bound operations (database queries, HTTP calls). FastAPI handles the event loop automatically.