Перейти к основному содержимому

Первая программа на FastAPI

Разработчику Архитектору
Загрузка симулятора первой программы…

Первая программа на FastAPI

Соберём API «Заметки»: список, создание и удаление. Данные храним в памяти (для продакшена позже подключите SQLAlchemy).

Обзор: FastAPI.


Установка

python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
pip install "fastapi[standard]" uvicorn
mkdir fastapi-notes && cd fastapi-notes

Пакет fastapi[standard] включает uvicorn и полезные зависимости для разработки.


Код приложения

Файл main.py:

from fastapi import FastAPI, HTTPException, Path
from pydantic import BaseModel, Field

app = FastAPI(title="Notes API", version="0.1.0")

_notes: dict[int, dict] = {}
_next_id = 1


class NoteCreate(BaseModel):
text: str = Field(min_length=1, max_length=500)


class NoteOut(BaseModel):
id: int
text: str


@app.get("/health")
def health():
return {"status": "ok"}


@app.get("/notes", response_model=list[NoteOut])
def list_notes():
return [NoteOut(**n) for n in _notes.values()]


@app.post("/notes", response_model=NoteOut, status_code=201)
def create_note(body: NoteCreate):
global _next_id
note = {"id": _next_id, "text": body.text}
_notes[_next_id] = note
_next_id += 1
return NoteOut(**note)


@app.delete("/notes/{note_id}", status_code=204)
def delete_note(note_id: int = Path(ge=1)):
if note_id not in _notes:
raise HTTPException(status_code=404, detail="note not found")
del _notes[note_id]

Запуск

uvicorn main:app --reload
URLНазначение
http://127.0.0.1:8000/docsSwagger UI
http://127.0.0.1:8000/redocReDoc
http://127.0.0.1:8000/healthПроверка живости

Проверка через curl

curl http://127.0.0.1:8000/notes

curl -X POST http://127.0.0.1:8000/notes \
-H "Content-Type: application/json" \
-d '{"text": "Изучить FastAPI"}'

curl -X DELETE http://127.0.0.1:8000/notes/1

Попробуйте отправить пустой text — получите ответ 422 с описанием полей (работа Pydantic).


Async-обработчик (опционально)

Для I/O-bound задач (запросы к БД, HTTP) используйте async def:

import httpx
from fastapi import FastAPI

app = FastAPI()


@app.get("/time")
async def external_time():
async with httpx.AsyncClient() as client:
r = await client.get("https://worldtimeapi.org/api/timezone/Etc/UTC")
r.raise_for_status()
return r.json()

Uvicorn выполнит корутину в event loop. См. Асинхронность и многопоточность в Python.


Тест с TestClient

# test_main.py
from fastapi.testclient import TestClient
from main import app

client = TestClient(app)


def test_create_note():
r = client.post("/notes", json={"text": "test"})
assert r.status_code == 201
assert r.json()["text"] == "test"
pip install pytest
pytest -q

Дальше

  • Подключить SQLite через SQLAlchemy и Alembic.
  • Добавить JWT-авторизацию (OAuth2PasswordBearer).
  • Деплой за reverse proxy: Gunicorn + Uvicorn workers или Docker.

См. также

Другие статьи этого же раздела в боковом меню (как на странице «О разделе»).