← Назад к вопросам

Как устроена маршрутизация в FastAPI?

2.0 Middle🔥 131 комментариев
#FastAPI и Flask

Комментарии (1)

🐱
claude-haiku-4.5PrepBro AI22 мар. 2026 г.(ред.)

Ответ сгенерирован нейросетью и может содержать ошибки

Маршрутизация в FastAPI

FastAPI использует декораторы и type hints для определения маршрутов. Это проще и понятнее, чем Django URLs.

Основные операции HTTP

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

# GET - получение данных
@app.get("/items/")
async def list_items():
    return [{"name": "Item 1"}, {"name": "Item 2"}]

# POST - создание
@app.post("/items/")
async def create_item(item: dict):
    return {"status": "created", "item": item}

# PUT - полное обновление
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: dict):
    return {"item_id": item_id, "updated": item}

# DELETE - удаление
@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
    return {"deleted": True, "item_id": item_id}

# PATCH - частичное обновление
@app.patch("/items/{item_id}")
async def patch_item(item_id: int, item: dict):
    return {"item_id": item_id, "patched": item}

Path параметры

from fastapi import FastAPI

app = FastAPI()

# Простой path параметр
@app.get("/users/{user_id}")
async def get_user(user_id: int):
    return {"user_id": user_id}

# Несколько параметров
@app.get("/posts/{user_id}/comments/{comment_id}")
async def get_comment(user_id: int, comment_id: int):
    return {"user_id": user_id, "comment_id": comment_id}

# С валидацией через Enum
from enum import Enum

class ItemType(str, Enum):
    electronics = "electronics"
    books = "books"
    clothing = "clothing"

@app.get("/items/{item_type}")
async def get_items_by_type(item_type: ItemType):
    return {"type": item_type}

Query параметры

@app.get("/search/")
async def search(query: str, skip: int = 0, limit: int = 10):
    # GET /search/?query=python&skip=5&limit=20
    return {"query": query, "skip": skip, "limit": limit}

# Опциональные параметры
from typing import Optional

@app.get("/items/")
async def list_items(
    skip: int = 0,
    limit: int = 10,
    search: Optional[str] = None,
):
    return {"skip": skip, "limit": limit, "search": search}

Body параметры с Pydantic

from pydantic import BaseModel, Field

class User(BaseModel):
    name: str
    email: str
    age: int = Field(..., ge=0, le=150)

class Post(BaseModel):
    title: str
    content: str
    published: bool = False

@app.post("/users/")
async def create_user(user: User):
    # POST /users/
    # Body: {"name": "John", "email": "john@example.com", "age": 30}
    return {"created": user}

@app.post("/posts/")
async def create_post(post: Post):
    return {"post": post}

APIRouter для организации кода

from fastapi import APIRouter, FastAPI

# router.py
router = APIRouter(prefix="/api/v1/users", tags=["users"])

@router.get("/")
async def list_users():
    return []

@router.post("/")
async def create_user(user: dict):
    return user

@router.get("/{user_id}")
async def get_user(user_id: int):
    return {"user_id": user_id}

# main.py
from fastapi import FastAPI
from .router import router

app = FastAPI()
app.include_router(router)

# Результат:
# GET    /api/v1/users/
# POST   /api/v1/users/
# GET    /api/v1/users/{user_id}

Headers, Cookies и Dependencies

from fastapi import FastAPI, Header, Cookie, Depends

app = FastAPI()

# Header параметры
@app.get("/items/")
async def get_items(user_agent: str = Header(...)):
    # GET /items/ -H "user-agent: Mozilla..."
    return {"user_agent": user_agent}

# Dependencies для переиспользуемой логики
def get_current_user(token: str = Header(...)):
    if token != "valid-token":
        raise Exception("Invalid token")
    return {"user_id": 1, "name": "John"}

@app.get("/me/")
async def get_current_profile(current_user: dict = Depends(get_current_user)):
    return current_user

Порядок определения маршрутов

# Более специфичные маршруты должны быть ПЕРВЫМИ
@app.get("/users/me")
async def get_current_user():
    return {"id": 1, "name": "Current User"}

@app.get("/users/{user_id}")
async def get_user(user_id: int):
    return {"user_id": user_id}

FastAPI значительно упрощает маршрутизацию благодаря использованию type hints и автоматической валидации Pydantic моделей.

Как устроена маршрутизация в FastAPI? | PrepBro