PythonのFastAPIは、高性能なREST APIを驚くほど少ないコードで構築できるモダンなWebフレームワークです。本記事では、インストールから本番デプロイまでを体系的に解説します。
FastAPIとは?なぜ今注目されているのか
FastAPIはSebastián Ramírezが開発したPython製のWebフレームワークで、以下の特徴があります。
- 高速性:NodeJS・Goに匹敵するパフォーマンス(Starlette + Uvicornベース)
- 型安全:Pydanticによる自動バリデーション
- 自動ドキュメント生成:Swagger UI・ReDocを標準搭載
- 非同期対応:async/awaitをネイティブサポート
- 少ないコード:DjangoやFlaskよりも大幅にコード量を削減
環境構築:インストール手順
# 仮想環境の作成
python -m venv venv
source venv/bin/activate # Mac/Linux
# venv\Scripts\activate # Windows
# FastAPIとUvicornのインストール
pip install fastapi uvicorn[standard]
# その他よく使うパッケージ
pip install pydantic sqlalchemy python-dotenv
最初のAPIを作成する
main.pyというファイルを作成し、以下のコードを記述します:
from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional
app = FastAPI(
title="Tech Athletes API",
description="エンジニア向けサンプルAPI",
version="1.0.0"
)
# データモデルの定義
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
is_available: bool = True
# GET エンドポイント
@app.get("/")
async def root():
return {"message": "Tech Athletes APIへようこそ!"}
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: Optional[str] = None):
return {"item_id": item_id, "query": q}
# POST エンドポイント
@app.post("/items/")
async def create_item(item: Item):
return {"item": item, "message": "アイテムを作成しました"}
# PUT エンドポイント
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
return {"item_id": item_id, "updated_item": item}
サーバーを起動するには:
uvicorn main:app --reload
ブラウザで http://localhost:8000/docs にアクセスすると、自動生成されたSwagger UIドキュメントが表示されます。
データベース連携:SQLAlchemy + SQLite
from sqlalchemy import create_engine, Column, Integer, String, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
DATABASE_URL = "sqlite:///./items.db"
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
class ItemDB(Base):
__tablename__ = "items"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, index=True)
description = Column(String, nullable=True)
price = Column(Float)
# テーブル作成
Base.metadata.create_all(bind=engine)
認証:JWT(JSON Web Token)の実装
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import JWTError, jwt
from passlib.context import CryptContext
from datetime import datetime, timedelta
SECRET_KEY = "your-secret-key-here"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
def create_access_token(data: dict):
to_encode = data.copy()
expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode.update({"exp": expire})
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
@app.post("/token")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
# ユーザー認証ロジックをここに実装
access_token = create_access_token(data={"sub": form_data.username})
return {"access_token": access_token, "token_type": "bearer"}
本番デプロイ:Dockerとの組み合わせ
# Dockerfile
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
FastAPI vs Flask vs Django:どれを選ぶべきか?
| 特徴 | FastAPI | Flask | Django |
|---|---|---|---|
| 学習曲線 | 中 | 低 | 高 |
| パフォーマンス | ★★★★★ | ★★★☆☆ | ★★★☆☆ |
| 型安全 | ネイティブ | 手動 | 手動 |
| 自動ドキュメント | あり | なし | なし |
| 適したユースケース | API専用 | 小規模Web | フルスタック |
まとめ
FastAPIはモダンなPython API開発のデファクトスタンダードになりつつあります。型ヒントによる安全性、自動ドキュメント生成、非同期処理のサポートを考えると、新規のAPI開発プロジェクトにはFastAPIを強くおすすめします。まずはローカル環境で試してみて、その使いやすさを体感してください。