FastAPI Introduction - High-Speed Python API Development

intermediate | 55 min read | 2024.12.28

What You’ll Learn in This Tutorial

✓ FastAPI setup
✓ Path parameters and queries
✓ Request body (Pydantic)
✓ Dependency injection
✓ Authentication and security

Step 1: Setup

python -m venv venv
source venv/bin/activate
pip install fastapi uvicorn pydantic

Step 2: Basic API

# main.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI()

class User(BaseModel):
    id: int
    name: str
    email: str

users: list[User] = []

@app.get("/")
def read_root():
    return {"message": "Hello, FastAPI!"}

@app.get("/users")
def get_users():
    return users

@app.get("/users/{user_id}")
def get_user(user_id: int):
    user = next((u for u in users if u.id == user_id), None)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return user

@app.post("/users", status_code=201)
def create_user(user: User):
    users.append(user)
    return user

Step 3: Start Server

uvicorn main:app --reload
# http://localhost:8000
# Swagger UI: http://localhost:8000/docs

Step 4: Query Parameters

from typing import Optional

@app.get("/items")
def get_items(
    skip: int = 0,
    limit: int = 10,
    q: Optional[str] = None
):
    items = get_all_items()
    if q:
        items = [i for i in items if q in i.name]
    return items[skip:skip + limit]

Step 5: Dependency Injection

from fastapi import Depends

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

@app.get("/users")
def get_users(db = Depends(get_db)):
    return db.query(User).all()

Step 6: Authentication

from fastapi.security import OAuth2PasswordBearer

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.get("/protected")
def protected_route(token: str = Depends(oauth2_scheme)):
    user = verify_token(token)
    return {"user": user}

Summary

FastAPI is a high-speed, type-safe Python API framework. Its automatic documentation generation and Pydantic-based validation are major attractions.

← Back to list