Step-by-step guide to building web APIs with FastAPI — type-annotated Python framework with auto-validation, interactive docs, and async support
Build modern, high-performance Python web APIs using FastAPI — a type-annotated framework with automatic validation, interactive documentation, and native async support.
Guides you through building FastAPI applications following the official tutorial structure:
1. **Core Concepts**: Path parameters, query parameters, request bodies, response models
2. **Validation**: Automatic data validation using Python type hints and Pydantic models
3. **Advanced Features**: Dependencies, security (OAuth2/JWT), middleware, background tasks
4. **Data Handling**: Form data, file uploads, cookies, headers, nested models
5. **Database Integration**: SQL databases with SQLAlchemy ORM patterns
6. **Production Features**: CORS, testing, deployment, Docker containers
7. **Architecture**: Multiple files, sub-applications, static files, templates
Create a virtual environment and install FastAPI with standard dependencies:
```bash
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install "fastapi[standard]"
```
**Note**: `fastapi[standard]` includes Uvicorn server and optional dependencies. Use `pip install fastapi` for minimal installation.
Create `main.py` with a basic endpoint:
```python
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
```
Run the development server:
```bash
fastapi dev main.py
```
Access interactive docs at `http://127.0.0.1:8000/docs` (Swagger UI) or `http://127.0.0.1:8000/redoc` (ReDoc).
```python
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
@app.get("/search")
async def search(q: str = "", limit: int = 10):
return {"query": q, "limit": limit}
```
**Type annotations provide**:
```python
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
@app.post("/items/")
async def create_item(item: Item):
return {"item": item, "total": item.price + (item.tax or 0)}
```
**Benefits**:
```python
from fastapi import FastAPI, status
from pydantic import BaseModel
app = FastAPI()
class ItemOut(BaseModel):
name: str
price: float
@app.post("/items/", response_model=ItemOut, status_code=status.HTTP_201_CREATED)
async def create_item(item: Item) -> ItemOut:
# Response model filters output fields
return item
```
```python
from fastapi import Depends, FastAPI, HTTPException
app = FastAPI()
async def get_current_user(token: str):
user = verify_token(token)
if not user:
raise HTTPException(status_code=401, detail="Invalid token")
return user
@app.get("/users/me")
async def read_users_me(current_user: User = Depends(get_current_user)):
return current_user
```
FastAPI includes OAuth2 helpers and JWT token utilities:
```python
from fastapi import FastAPI, Depends
from fastapi.security import OAuth2PasswordBearer
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@app.get("/items/")
async def read_items(token: str = Depends(oauth2_scheme)):
# Validate token and return items
return {"token": token}
```
```python
from fastapi import FastAPI, Depends
from sqlalchemy.orm import Session
app = FastAPI()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.get("/users/{user_id}")
async def read_user(user_id: int, db: Session = Depends(get_db)):
user = db.query(User).filter(User.id == user_id).first()
return user
```
FastAPI provides `TestClient` (built on Starlette's test client):
```python
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def test_read_main():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"message": "Hello World"}
```
For production, use `fastapi run` (Uvicorn with standard settings):
```bash
fastapi run main.py
```
Or with Docker:
```dockerfile
FROM python:3.11
WORKDIR /code
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY ./app /code/app
CMD ["fastapi", "run", "app/main.py", "--port", "80"]
```
Follow the official FastAPI tutorial sections in order:
1. **Basics**: First Steps → Path/Query Parameters → Request Body
2. **Validation**: String/Numeric Validations → Extra Data Types
3. **Advanced Data**: Nested Models → Form Data → File Uploads
4. **Structure**: Response Models → Dependencies → Error Handling
5. **Security**: OAuth2 Password Flow → JWT Tokens
6. **Production**: Middleware → CORS → SQL Databases → Background Tasks → Testing
**File uploads**:
```python
from fastapi import File, UploadFile
@app.post("/files/")
async def create_file(file: UploadFile = File(...)):
return {"filename": file.filename}
```
**Background tasks**:
```python
from fastapi import BackgroundTasks
def send_email(email: str):
# Send email logic
pass
@app.post("/send-notification/")
async def send_notification(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(send_email, email)
return {"message": "Notification sent"}
```
**CORS middleware**:
```python
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
```
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/fastapi-development/raw