コンテンツにスキップ

FastAPI

出典: フリー教科書『ウィキブックス(Wikibooks)』

はじめに

[編集]

FastAPIは、Pythonで高速かつ効率的なWeb APIを構築するためのモダンなフレームワークです。このハンドブックでは、FastAPIの基本から応用までを解説し、実践的な使用方法を紹介します。

FastAPIとは

[編集]

FastAPIは、PythonのWebフレームワークで、以下の特徴を持っています。

  • 高速: StarlettePydanticを基盤に、高いパフォーマンスを実現。
  • 簡単: シンプルなコードで強力な機能を提供。
  • モダン: OpenAPIJSON Schemaをサポート。

FastAPIの特徴

[編集]

高速なパフォーマンス

[編集]

FastAPIは、非同期処理をサポートし、高いパフォーマンスを実現します。

自動ドキュメント生成

[編集]

OpenAPIとSwagger UIをサポートし、APIドキュメントを自動生成します。

データバリデーション

[編集]

Pydanticを利用して、リクエストデータのバリデーションを行います。

FastAPIのインストール

[編集]

FastAPIは、pipを使って簡単にインストールできます。

pip install fastapi

また、開発用サーバーとしてuvicornもインストールします。

pip install uvicorn

FastAPIの基本的な使い方

[編集]

FastAPIは、シンプルなコードでAPIを構築できます。以下は、基本的な使い方の例です。

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

このコードをmain.pyとして保存し、以下のコマンドで実行します。

uvicorn main:app --reload

FastAPIのルーティング

[編集]

FastAPIでは、@app.get@app.postなどのデコレータを使ってルーティングを定義します。

例: GETリクエスト

[編集]
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}

例: POSTリクエスト

[編集]
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float

@app.post("/items/")
def create_item(item: Item):
    return item

FastAPIのリクエストとレスポンス

[編集]

FastAPIでは、リクエストとレスポンスを簡単に扱えます。

リクエストパラメータ

[編集]
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}

レスポンスモデル

[編集]
@app.get("/items/{item_id}", response_model=Item)
def read_item(item_id: int):
    return {"item_id": item_id, "name": "Foo", "price": 42.0}

FastAPIのデータバリデーション

[編集]

FastAPIは、Pydanticを利用してデータのバリデーションを行います。

例: データモデル

[編集]
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float
    is_offer: bool = None

例: バリデーション

[編集]
@app.post("/items/")
def create_item(item: Item):
    return item

FastAPIの依存性注入

[編集]

FastAPIでは、依存性注入を簡単に実装できます。

例: 依存性の定義

[編集]
from fastapi import Depends

def common_parameters(q: str = None, skip: int = 0, limit: int = 100):
    return {"q": q, "skip": skip, "limit": limit}

@app.get("/items/")
def read_items(commons: dict = Depends(common_parameters)):
    return commons

FastAPIのミドルウェア

[編集]

FastAPIでは、ミドルウェアを使ってリクエストとレスポンスの処理を拡張できます。

例: ミドルウェアの追加

[編集]
from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

FastAPIのエラーハンドリング

[編集]

FastAPIでは、エラーハンドリングを簡単に実装できます。

例: カスタムエラーハンドリング

[編集]
from fastapi import HTTPException

@app.get("/items/{item_id}")
def read_item(item_id: int):
    if item_id == 42:
        raise HTTPException(status_code=404, detail="Item not found")
    return {"item_id": item_id}

FastAPIのセキュリティ

[編集]

FastAPIでは、セキュリティ機能を簡単に実装できます。

例: OAuth2とJWT

[編集]
from fastapi.security import OAuth2PasswordBearer

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.get("/items/")
def read_items(token: str = Depends(oauth2_scheme)):
    return {"token": token}

FastAPIのテスト

[編集]

FastAPIでは、テストを簡単に実装できます。

例: テストコード

[編集]
from fastapi.testclient import TestClient

client = TestClient(app)

def test_read_root():
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"Hello": "World"}

FastAPIのデプロイ

[編集]

FastAPIは、以下の方法でデプロイできます。

  • Docker: Dockerコンテナとしてデプロイ。
  • Heroku: Herokuにデプロイ。
  • AWS: AWS LambdaやECSにデプロイ。

例: Dockerfile

[編集]
FROM tiangolo/uvicorn-gunicorn-fastapi:python3.8

COPY ./app /app

FastAPIのユースケース

[編集]
  • マイクロサービス: 高速で軽量なAPIを構築。
  • リアルタイムアプリケーション: 非同期処理を活用。
  • データサイエンス: 機械学習モデルのAPI化。

参考文献

[編集]

このハンドブックが、FastAPIの理解と実践に役立つことを願っています。FastAPIを活用し、高性能なWeb APIを開発しましょう!