We use cookies to understand how the site is used and to display ads. Analytics and advertising only run after you accept. You can change your choice anytime. Privacy policy

Skip to content
devvkit
$devvkit learn --librarie fastapi-guide

FastAPI Guide

[python][api][async]
Python
Install
pip install fastapi uvicorn

FastAPI uses Python type hints for validation (Pydantic), serialization, and OpenAPI generation.

Async-first but works with sync code. Uvicorn rivals Node.js performance.

Auto-generated Swagger UI at /docs and ReDoc at /redoc: every endpoint documented.

Setup

Basic app· Minimal app.
from fastapi import FastAPI
app = FastAPI()
@app.get('/')
def root():
    return {'Hello': 'World'}
# uvicorn main:app --reload

Path Operations

Path param· URL variable.
@app.get('/users/{user_id}')
def get_user(user_id: int):
    return {'user_id': user_id}
Query params· Query string.
@app.get('/search')
def search(q: str = '', limit: int = 10):
    return {'query': q, 'limit': limit}

Request Validation

Request body· Pydantic validation.
from pydantic import BaseModel
class UserCreate(BaseModel):
    name: str
    email: str
    age: int | None = None

@app.post('/users')
def create_user(user: UserCreate):
    return {'id': 1, **user.model_dump()}

Response Models

Response model· Typed response.
@app.get('/users', response_model=list[UserResponse])
def list_users():
    return db.get_users()  # auto-serialized

Dependencies

Dependency injection· Auth dependency.
from fastapi import Depends, HTTPException
async def get_current_user(token: str = Depends(HTTPBearer())):
    user = verify_token(token)
    if not user: raise HTTPException(status_code=401)
    return user

@app.get('/profile')
def profile(user: User = Depends(get_current_user)):
    return user

Testing

TestClient· Integration test.
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def test_root():
    resp = client.get('/')
    assert resp.status_code == 200
    assert resp.json() == {'Hello': 'World'}