FastAPI の中核概念
FastAPI は、API を構築するためのモダンで高速(高性能)な Python Web フレームワークです。標準の Python 型ヒントに基づいており、Starlette と Pydantic を使用して構築されています。
主な特徴
- 高性能:NodeJS や Go に匹敵し、最速の Python フレームワークの一つです
- 高速開発:開発速度が約 200%~300% 向上します
- エラー削減:人為的エラーを約 40% 削減します
- 直感的:強力なエディタサポートにより、どこでも自動補完が使えます
- シンプル:使いやすく学びやすい、ドキュメントを読む時間を減らせます
ASGI と非同期プログラミング
ASGI とは?
ASGI(Asynchronous Server Gateway Interface)は、Python の非同期 Web サーバーとアプリケーションの間の標準インターフェースです。
WSGI と ASGI の比較:
例
# WSGI アプリケーション(同期)- 従来の Flask スタイル
def wsgi_app(environ, start_response):
status = '200 OK'
response_headers = [('Content-type', 'text/plain')]
start_response(status, response_headers)
return [b'Hello World']
# ASGI アプリケーション(非同期)- FastAPI スタイル
async def asgi_app(scope, receive, send):
await send({
'type': 'http.response.start',
'status': 200,
'headers': [(b'content-type', b'text/plain')],
})
await send({
'type': 'http.response.body',
'body': b'Hello World',
})
def wsgi_app(environ, start_response):
status = '200 OK'
response_headers = [('Content-type', 'text/plain')]
start_response(status, response_headers)
return [b'Hello World']
# ASGI アプリケーション(非同期)- FastAPI スタイル
async def asgi_app(scope, receive, send):
await send({
'type': 'http.response.start',
'status': 200,
'headers': [(b'content-type', b'text/plain')],
})
await send({
'type': 'http.response.body',
'body': b'Hello World',
})
非同期プログラミングの中核概念
同期 vs 非同期実行:
例
import asyncio
import time
import httpx
# 同期方式 - ブロッキング実行
def sync_fetch_data():
start_time = time.time()
# 3つのネットワークリクエストをシミュレート
time.sleep(1) # 最初のリクエスト
time.sleep(1) # 2番目のリクエスト
time.sleep(1) # 3番目のリクエスト
print(f"同期実行の所要時間: {time.time() - start_time:.2f}秒") # 約3秒
# 非同期方式 - 並行実行
async def async_fetch_data():
start_time = time.time()
# 3つのリクエストを並行実行
await asyncio.gather(
asyncio.sleep(1), # 最初のリクエスト
asyncio.sleep(1), # 2番目のリクエスト
asyncio.sleep(1), # 3番目のリクエスト
)
print(f"非同期実行の所要時間: {time.time() - start_time:.2f}秒") # 約1秒
# 実行例
sync_fetch_data() # 出力: 同期実行の所要時間: 3.00秒
asyncio.run(async_fetch_data()) # 出力: 非同期実行の所要時間: 1.00秒
import time
import httpx
# 同期方式 - ブロッキング実行
def sync_fetch_data():
start_time = time.time()
# 3つのネットワークリクエストをシミュレート
time.sleep(1) # 最初のリクエスト
time.sleep(1) # 2番目のリクエスト
time.sleep(1) # 3番目のリクエスト
print(f"同期実行の所要時間: {time.time() - start_time:.2f}秒") # 約3秒
# 非同期方式 - 並行実行
async def async_fetch_data():
start_time = time.time()
# 3つのリクエストを並行実行
await asyncio.gather(
asyncio.sleep(1), # 最初のリクエスト
asyncio.sleep(1), # 2番目のリクエスト
asyncio.sleep(1), # 3番目のリクエスト
)
print(f"非同期実行の所要時間: {time.time() - start_time:.2f}秒") # 約1秒
# 実行例
sync_fetch_data() # 出力: 同期実行の所要時間: 3.00秒
asyncio.run(async_fetch_data()) # 出力: 非同期実行の所要時間: 1.00秒
FastAPI での非同期パス操作:
例
from fastapi import FastAPI
import asyncio
app = FastAPI()
# 同期パス操作
@app.get("/sync")
def sync_endpoint():
# 同期操作はアプリ全体をブロックします
time.sleep(2)
return {"message": "同期レスポンス"}
# 非同期パス操作(推奨)
@app.get("/async")
async def async_endpoint():
# 非同期操作は他のリクエストをブロックしません
await asyncio.sleep(2)
return {"message": "非同期レスポンス"}
# 非同期データベース操作の例
@app.get("/users/{user_id}")
async def get_user(user_id: int):
# 非同期データベースクエリ
user = await database.fetch_one(
"SELECT * FROM users WHERE id = :user_id",
{"user_id": user_id}
)
return user
import asyncio
app = FastAPI()
# 同期パス操作
@app.get("/sync")
def sync_endpoint():
# 同期操作はアプリ全体をブロックします
time.sleep(2)
return {"message": "同期レスポンス"}
# 非同期パス操作(推奨)
@app.get("/async")
async def async_endpoint():
# 非同期操作は他のリクエストをブロックしません
await asyncio.sleep(2)
return {"message": "非同期レスポンス"}
# 非同期データベース操作の例
@app.get("/users/{user_id}")
async def get_user(user_id: int):
# 非同期データベースクエリ
user = await database.fetch_one(
"SELECT * FROM users WHERE id = :user_id",
{"user_id": user_id}
)
return user
いつ非同期を使うか?
非同期に適したシナリオ:
- データベース操作
- ネットワークリクエスト(API 呼び出し)
- ファイル I/O 操作
- 長時間待機する操作
非同期に適さないシナリオ:
- CPU集約型計算
- 単純なデータ処理
- I/O 待機のない操作
例
# 良い非同期の使い方
@app.get("/weather")
async def get_weather():
async with httpx.AsyncClient() as client:
response = await client.get("https://api.weather.com/data")
return response.json()
# 不要な非同期(I/O 待機なし)
@app.get("/calculate")
def calculate_sync(): # 同期のままでよい
result = sum(range(1000000))
return {"result": result}
@app.get("/weather")
async def get_weather():
async with httpx.AsyncClient() as client:
response = await client.get("https://api.weather.com/data")
return response.json()
# 不要な非同期(I/O 待機なし)
@app.get("/calculate")
def calculate_sync(): # 同期のままでよい
result = sum(range(1000000))
return {"result": result}
REST API設計原則
REST の基本概念
REST(Representational State Transfer)は Web API の設計スタイルであり、以下を重視します:
- リソース指向:URL がリソースを表す
- ステートレス:各リクエストは独立している
- 統一インターフェース:標準の HTTP メソッドを使用する
- 階層化システム:キャッシュ、ロードバランシングなどをサポート
RESTful URL 設計
良い URL 設計の例:
例
from fastapi import FastAPI, HTTPException, status
from pydantic import BaseModel
from typing import List, Optional
app = FastAPI()
# リソースコレクションと単一リソース
@app.get("/users") # GET /users - ユーザーリストを取得
async def get_users():
return users_db
@app.get("/users/{user_id}") # GET /users/123 - 特定のユーザーを取得
async def get_user(user_id: int):
return find_user(user_id)
@app.post("/users") # POST /users - 新しいユーザーを作成
async def create_user(user: UserCreate):
return create_new_user(user)
@app.put("/users/{user_id}") # PUT /users/123 - ユーザーを完全更新
async def update_user(user_id: int, user: UserUpdate):
return update_existing_user(user_id, user)
@app.patch("/users/{user_id}") # PATCH /users/123 - ユーザーを部分更新
async def patch_user(user_id: int, user: UserPatch):
return patch_existing_user(user_id, user)
@app.delete("/users/{user_id}") # DELETE /users/123 - ユーザーを削除
async def delete_user(user_id: int):
return delete_existing_user(user_id)
# ネストされたリソース
@app.get("/users/{user_id}/posts") # ユーザーのすべての記事を取得
async def get_user_posts(user_id: int):
return get_posts_by_user(user_id)
@app.post("/users/{user_id}/posts") # ユーザーに新しい記事を作成
async def create_user_post(user_id: int, post: PostCreate):
return create_post_for_user(user_id, post)
from pydantic import BaseModel
from typing import List, Optional
app = FastAPI()
# リソースコレクションと単一リソース
@app.get("/users") # GET /users - ユーザーリストを取得
async def get_users():
return users_db
@app.get("/users/{user_id}") # GET /users/123 - 特定のユーザーを取得
async def get_user(user_id: int):
return find_user(user_id)
@app.post("/users") # POST /users - 新しいユーザーを作成
async def create_user(user: UserCreate):
return create_new_user(user)
@app.put("/users/{user_id}") # PUT /users/123 - ユーザーを完全更新
async def update_user(user_id: int, user: UserUpdate):
return update_existing_user(user_id, user)
@app.patch("/users/{user_id}") # PATCH /users/123 - ユーザーを部分更新
async def patch_user(user_id: int, user: UserPatch):
return patch_existing_user(user_id, user)
@app.delete("/users/{user_id}") # DELETE /users/123 - ユーザーを削除
async def delete_user(user_id: int):
return delete_existing_user(user_id)
# ネストされたリソース
@app.get("/users/{user_id}/posts") # ユーザーのすべての記事を取得
async def get_user_posts(user_id: int):
return get_posts_by_user(user_id)
@app.post("/users/{user_id}/posts") # ユーザーに新しい記事を作成
async def create_user_post(user_id: int, post: PostCreate):
return create_post_for_user(user_id, post)
URL設計原則:
好的设计 GET /api/v1/users # 获取用户列表 GET /api/v1/users/123 # 获取用户 123 POST /api/v1/users # 创建用户 GET /api/v1/users/123/orders # 获取用户 123 的订单 # 不好的设计 GET /api/v1/getAllUsers # 动词不应该在 URL 中 GET /api/v1/user/123 # 集合名应该用复数 POST /api/v1/createUser # URL 中包含动作 GET /api/v1/users-orders-123 # 关系不清晰
リソースの階層関係
例
# ユーザーと記事の関係設計
class User(BaseModel):
id: int
name: str
email: str
class Post(BaseModel):
id: int
title: str
content: str
author_id: int
# 主リソース操作
@app.get("/users")
async def list_users() -> List[User]:
return users
@app.get("/posts")
async def list_posts() -> List[Post]:
return posts
# 関連リソース操作
@app.get("/users/{user_id}/posts")
async def get_user_posts(user_id: int) -> List[Post]:
"""特定のユーザーのすべての記事を取得"""
return [post for post in posts if post.author_id == user_id]
@app.get("/posts/{post_id}/author")
async def get_post_author(post_id: int) -> User:
"""記事の作成者情報を取得"""
post = find_post(post_id)
if not post:
raise HTTPException(status_code=404, detail="Post not found")
return find_user(post.author_id)
class User(BaseModel):
id: int
name: str
email: str
class Post(BaseModel):
id: int
title: str
content: str
author_id: int
# 主リソース操作
@app.get("/users")
async def list_users() -> List[User]:
return users
@app.get("/posts")
async def list_posts() -> List[Post]:
return posts
# 関連リソース操作
@app.get("/users/{user_id}/posts")
async def get_user_posts(user_id: int) -> List[Post]:
"""特定のユーザーのすべての記事を取得"""
return [post for post in posts if post.author_id == user_id]
@app.get("/posts/{post_id}/author")
async def get_post_author(post_id: int) -> User:
"""記事の作成者情報を取得"""
post = find_post(post_id)
if not post:
raise HTTPException(status_code=404, detail="Post not found")
return find_user(post.author_id)
HTTP メソッドとステータスコード
HTTP メソッドの意味論
例
from fastapi import FastAPI, status, HTTPException
from fastapi.responses import JSONResponse
app = FastAPI()
# GET - 安全かつ冪等
@app.get("/users/{user_id}")
async def get_user(user_id: int):
"""リソースを取得し、サーバーの状態を変更しない"""
user = find_user(user_id)
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="User not found"
)
return user
# POST - 安全でなく非冪等
@app.post("/users", status_code=status.HTTP_201_CREATED)
async def create_user(user: UserCreate):
"""新しいリソースを作成"""
if user_exists(user.email):
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="User already exists"
)
new_user = create_new_user(user)
return new_user
# PUT - 安全ではないが冪等
@app.put("/users/{user_id}")
async def replace_user(user_id: int, user: UserUpdate):
"""リソースを完全に置き換える"""
if not user_exists(user_id):
# PUT はリソースを作成できる
return create_user_with_id(user_id, user)
return replace_existing_user(user_id, user)
# PATCH - 安全でなく、通常は非冪等
@app.patch("/users/{user_id}")
async def update_user(user_id: int, user: UserPatch):
"""リソースを部分更新"""
existing_user = find_user(user_id)
if not existing_user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="User not found"
)
return patch_user_fields(existing_user, user)
# DELETE - 安全ではないが冪等
@app.delete("/users/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_user(user_id: int):
"""リソースを削除"""
if not user_exists(user_id):
# 冪等性:存在しないリソースを削除しても成功を返す
return JSONResponse(status_code=status.HTTP_204_NO_CONTENT)
delete_existing_user(user_id)
return JSONResponse(status_code=status.HTTP_204_NO_CONTENT)
from fastapi.responses import JSONResponse
app = FastAPI()
# GET - 安全かつ冪等
@app.get("/users/{user_id}")
async def get_user(user_id: int):
"""リソースを取得し、サーバーの状態を変更しない"""
user = find_user(user_id)
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="User not found"
)
return user
# POST - 安全でなく非冪等
@app.post("/users", status_code=status.HTTP_201_CREATED)
async def create_user(user: UserCreate):
"""新しいリソースを作成"""
if user_exists(user.email):
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="User already exists"
)
new_user = create_new_user(user)
return new_user
# PUT - 安全ではないが冪等
@app.put("/users/{user_id}")
async def replace_user(user_id: int, user: UserUpdate):
"""リソースを完全に置き換える"""
if not user_exists(user_id):
# PUT はリソースを作成できる
return create_user_with_id(user_id, user)
return replace_existing_user(user_id, user)
# PATCH - 安全でなく、通常は非冪等
@app.patch("/users/{user_id}")
async def update_user(user_id: int, user: UserPatch):
"""リソースを部分更新"""
existing_user = find_user(user_id)
if not existing_user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="User not found"
)
return patch_user_fields(existing_user, user)
# DELETE - 安全ではないが冪等
@app.delete("/users/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_user(user_id: int):
"""リソースを削除"""
if not user_exists(user_id):
# 冪等性:存在しないリソースを削除しても成功を返す
return JSONResponse(status_code=status.HTTP_204_NO_CONTENT)
delete_existing_user(user_id)
return JSONResponse(status_code=status.HTTP_204_NO_CONTENT)
HTTP ステータスコードの使用
例
from fastapi import status
# 2xx 成功レスポンス
@app.post("/users", status_code=status.HTTP_201_CREATED) # 201 Created
@app.get("/users") # 200 OK(デフォルト)
@app.delete("/users/{user_id}", status_code=status.HTTP_204_NO_CONTENT) # 204 No Content
# 4xx クライアントエラー
@app.get("/users/{user_id}")
async def get_user(user_id: int):
if user_id < 1:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, # 400 Bad Request
detail="User ID must be positive"
)
user = find_user(user_id)
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, # 404 Not Found
detail="User not found"
)
return user
# ビジネスロジックエラー
@app.post("/users/{user_id}/follow")
async def follow_user(user_id: int, current_user_id: int):
if user_id == current_user_id:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, # 422 Unprocessable Entity
detail="Cannot follow yourself"
)
if is_already_following(current_user_id, user_id):
raise HTTPException(
status_code=status.HTTP_409_CONFLICT, # 409 Conflict
detail="Already following this user"
)
# 5xx サーバーエラー(通常は例外ハンドラーで処理)
@app.exception_handler(Exception)
async def general_exception_handler(request, exc):
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, # 500 Internal Server Error
content={"detail": "Internal server error"}
)
# 2xx 成功レスポンス
@app.post("/users", status_code=status.HTTP_201_CREATED) # 201 Created
@app.get("/users") # 200 OK(デフォルト)
@app.delete("/users/{user_id}", status_code=status.HTTP_204_NO_CONTENT) # 204 No Content
# 4xx クライアントエラー
@app.get("/users/{user_id}")
async def get_user(user_id: int):
if user_id < 1:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, # 400 Bad Request
detail="User ID must be positive"
)
user = find_user(user_id)
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, # 404 Not Found
detail="User not found"
)
return user
# ビジネスロジックエラー
@app.post("/users/{user_id}/follow")
async def follow_user(user_id: int, current_user_id: int):
if user_id == current_user_id:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, # 422 Unprocessable Entity
detail="Cannot follow yourself"
)
if is_already_following(current_user_id, user_id):
raise HTTPException(
status_code=status.HTTP_409_CONFLICT, # 409 Conflict
detail="Already following this user"
)
# 5xx サーバーエラー(通常は例外ハンドラーで処理)
@app.exception_handler(Exception)
async def general_exception_handler(request, exc):
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, # 500 Internal Server Error
content={"detail": "Internal server error"}
)
よく使うステータスコード早見表:
# 成功状态码 200 OK # 请求成功 201 Created # 资源创建成功 204 No Content # 成功但无内容返回 206 Partial Content # 部分内容(分页、断点续传) # 重定向 301 Moved Permanently # 永久重定向 302 Found # 临时重定向 304 Not Modified # 资源未修改(缓存) # 客户端错误 400 Bad Request # 请求格式错误 401 Unauthorized # 未认证 403 Forbidden # 已认证但无权限 404 Not Found # 资源不存在 405 Method Not Allowed # HTTP 方法不允许 409 Conflict # 资源冲突 422 Unprocessable Entity # 数据验证失败 429 Too Many Requests # 请求过于频繁 # 服务器错误 500 Internal Server Error # 服务器内部错误 502 Bad Gateway # 网关错误 503 Service Unavailable # 服务不可用
JSON データ形式
JSON の基本とベストプラクティス
例
from datetime import datetime
from decimal import Decimal
from typing import Optional, List
from pydantic import BaseModel, Field
import json
# JSON データ形式の仕様
class UserResponse(BaseModel):
id: int
username: str
email: str
full_name: Optional[str] = None
is_active: bool = True
created_at: datetime
updated_at: Optional[datetime] = None
# JSON シリアライズ設定
class Config:
# フィールドエイリアスの使用を許可
allow_population_by_field_name = True
# JSON エンコーダー
json_encoders = {
datetime: lambda v: v.isoformat(),
Decimal: lambda v: float(v)
}
# レスポンス形式の標準化
class APIResponse(BaseModel):
"""標準 API レスポンス形式"""
success: bool = True
message: str = "操作に成功しました"
data: Optional[dict] = None
errors: Optional[List[str]] = None
timestamp: datetime = Field(default_factory=datetime.now)
# ページネーションレスポンス形式
class PaginatedResponse(BaseModel):
items: List[dict]
total: int
page: int
size: int
pages: int
@app.get("/users", response_model=PaginatedResponse)
async def get_users(page: int = 1, size: int = 10):
"""ページネーションされたユーザーリストを返す"""
users = get_users_paginated(page, size)
total = count_users()
return PaginatedResponse(
items=users,
total=total,
page=page,
size=size,
pages=(total + size - 1) // size
)
from decimal import Decimal
from typing import Optional, List
from pydantic import BaseModel, Field
import json
# JSON データ形式の仕様
class UserResponse(BaseModel):
id: int
username: str
email: str
full_name: Optional[str] = None
is_active: bool = True
created_at: datetime
updated_at: Optional[datetime] = None
# JSON シリアライズ設定
class Config:
# フィールドエイリアスの使用を許可
allow_population_by_field_name = True
# JSON エンコーダー
json_encoders = {
datetime: lambda v: v.isoformat(),
Decimal: lambda v: float(v)
}
# レスポンス形式の標準化
class APIResponse(BaseModel):
"""標準 API レスポンス形式"""
success: bool = True
message: str = "操作に成功しました"
data: Optional[dict] = None
errors: Optional[List[str]] = None
timestamp: datetime = Field(default_factory=datetime.now)
# ページネーションレスポンス形式
class PaginatedResponse(BaseModel):
items: List[dict]
total: int
page: int
size: int
pages: int
@app.get("/users", response_model=PaginatedResponse)
async def get_users(page: int = 1, size: int = 10):
"""ページネーションされたユーザーリストを返す"""
users = get_users_paginated(page, size)
total = count_users()
return PaginatedResponse(
items=users,
total=total,
page=page,
size=size,
pages=(total + size - 1) // size
)
JSON Schema とデータ検証
例
from pydantic import BaseModel, validator, Field
from typing import Optional, List
from enum import Enum
class UserRole(str, Enum):
ADMIN = "admin"
USER = "user"
MODERATOR = "moderator"
class UserCreate(BaseModel):
username: str = Field(..., min_length=3, max_length=50, description="ユーザー名")
email: str = Field(..., regex=r'^[\w\.-]+@[\w\.-]+\.\w+$', description="メールアドレス")
password: str = Field(..., min_length=8, description="パスワード")
full_name: Optional[str] = Field(None, max_length=100, description="フルネーム")
role: UserRole = Field(UserRole.USER, description="ユーザーロール")
age: Optional[int] = Field(None, ge=0, le=150, description="年齢")
@validator('username')
def username_must_be_alphanumeric(cls, v):
if not v.isalnum():
raise ValueError('ユーザー名は英字と数字のみ使用できます')
return v
@validator('password')
def password_strength(cls, v):
if not any(c.isupper() for c in v):
raise ValueError('パスワードには少なくとも1つの大文字を含める必要があります')
if not any(c.islower() for c in v):
raise ValueError('パスワードには少なくとも1つの小文字を含める必要があります')
if not any(c.isdigit() for c in v):
raise ValueError('パスワードには少なくとも1つの数字を含める必要があります')
return v
class Config:
# JSONスキーマの例を生成
schema_extra = {
"example": {
"username": "johndoe",
"email": "john@example.com",
"password": "SecurePass123",
"full_name": "John Doe",
"role": "user",
"age": 30
}
}
# カスタムバリデーターを使用
@app.post("/users", response_model=UserResponse)
async def create_user(user: UserCreate):
"""データ検証を含む新規ユーザーを作成"""
# Pydanticが入力データを自動検証
return await create_new_user(user)
from typing import Optional, List
from enum import Enum
class UserRole(str, Enum):
ADMIN = "admin"
USER = "user"
MODERATOR = "moderator"
class UserCreate(BaseModel):
username: str = Field(..., min_length=3, max_length=50, description="ユーザー名")
email: str = Field(..., regex=r'^[\w\.-]+@[\w\.-]+\.\w+$', description="メールアドレス")
password: str = Field(..., min_length=8, description="パスワード")
full_name: Optional[str] = Field(None, max_length=100, description="フルネーム")
role: UserRole = Field(UserRole.USER, description="ユーザーロール")
age: Optional[int] = Field(None, ge=0, le=150, description="年齢")
@validator('username')
def username_must_be_alphanumeric(cls, v):
if not v.isalnum():
raise ValueError('ユーザー名は英字と数字のみ使用できます')
return v
@validator('password')
def password_strength(cls, v):
if not any(c.isupper() for c in v):
raise ValueError('パスワードには少なくとも1つの大文字を含める必要があります')
if not any(c.islower() for c in v):
raise ValueError('パスワードには少なくとも1つの小文字を含める必要があります')
if not any(c.isdigit() for c in v):
raise ValueError('パスワードには少なくとも1つの数字を含める必要があります')
return v
class Config:
# JSONスキーマの例を生成
schema_extra = {
"example": {
"username": "johndoe",
"email": "john@example.com",
"password": "SecurePass123",
"full_name": "John Doe",
"role": "user",
"age": 30
}
}
# カスタムバリデーターを使用
@app.post("/users", response_model=UserResponse)
async def create_user(user: UserCreate):
"""データ検証を含む新規ユーザーを作成"""
# Pydanticが入力データを自動検証
return await create_new_user(user)
エラーレスポンス形式
例
class ErrorDetail(BaseModel):
field: str
message: str
code: str
class ErrorResponse(BaseModel):
error: str
message: str
details: Optional[List[ErrorDetail]] = None
timestamp: datetime = Field(default_factory=datetime.now)
# カスタム例外処理
from fastapi import Request
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
errors = []
for error in exc.errors():
errors.append(ErrorDetail(
field='.'.join(str(x) for x in error['loc']),
message=error['msg'],
code=error['type']
))
return JSONResponse(
status_code=422,
content=ErrorResponse(
error="Validation Error",
message="リクエストデータの検証に失敗しました",
details=errors
).dict()
)
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
return JSONResponse(
status_code=exc.status_code,
content=ErrorResponse(
error=f"HTTP {exc.status_code}",
message=exc.detail
).dict()
)
field: str
message: str
code: str
class ErrorResponse(BaseModel):
error: str
message: str
details: Optional[List[ErrorDetail]] = None
timestamp: datetime = Field(default_factory=datetime.now)
# カスタム例外処理
from fastapi import Request
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
errors = []
for error in exc.errors():
errors.append(ErrorDetail(
field='.'.join(str(x) for x in error['loc']),
message=error['msg'],
code=error['type']
))
return JSONResponse(
status_code=422,
content=ErrorResponse(
error="Validation Error",
message="リクエストデータの検証に失敗しました",
details=errors
).dict()
)
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
return JSONResponse(
status_code=exc.status_code,
content=ErrorResponse(
error=f"HTTP {exc.status_code}",
message=exc.detail
).dict()
)
FastAPI 特有の概念
自動ドキュメント生成
例
from fastapi import FastAPI, Query, Path, Body
from fastapi.openapi.utils import get_openapi
app = FastAPI(
title="マイAPI",
description="これはFastAPIの機能を示すサンプルAPIです",
version="1.0.0",
terms_of_service="http://example.com/terms/",
contact={
"name": "開発者",
"url": "http://example.com/contact/",
"email": "developer@example.com",
},
license_info={
"name": "MIT",
"url": "https://opensource.org/licenses/MIT",
},
)
@app.get(
"/users/{user_id}",
summary="ユーザー情報を取得",
description="ユーザーIDに基づいてユーザーの詳細情報を取得します",
response_description="ユーザー情報オブジェクト",
tags=["ユーザー管理"]
)
async def get_user(
user_id: int = Path(..., title="ユーザーID", description="取得するユーザーID", ge=1),
include_posts: bool = Query(False, title="記事を含む", description="ユーザーの記事リストを含めるかどうか")
):
"""
ユーザー情報を取得:
- **user_id**: ユーザーの一意の識別子
- **include_posts**: レスポンスにユーザーの記事リストを含めるかどうか
ユーザーの基本情報を返します。include_postsがTrueの場合は、記事リストも含まれます。
"""
user = find_user(user_id)
if include_posts:
user.posts = get_user_posts(user_id)
return user
# カスタムOpenAPIスキーマ
def custom_openapi():
if app.openapi_schema:
return app.openapi_schema
openapi_schema = get_openapi(
title="カスタムAPIドキュメント",
version="2.5.0",
description="これはカスタムのOpenAPIスキーマです",
routes=app.routes,
)
# カスタム情報を追加
openapi_schema["info"]["x-logo"] = {
"url": "https://example.com/logo.png"
}
app.openapi_schema = openapi_schema
return app.openapi_schema
app.openapi = custom_openapi
from fastapi.openapi.utils import get_openapi
app = FastAPI(
title="マイAPI",
description="これはFastAPIの機能を示すサンプルAPIです",
version="1.0.0",
terms_of_service="http://example.com/terms/",
contact={
"name": "開発者",
"url": "http://example.com/contact/",
"email": "developer@example.com",
},
license_info={
"name": "MIT",
"url": "https://opensource.org/licenses/MIT",
},
)
@app.get(
"/users/{user_id}",
summary="ユーザー情報を取得",
description="ユーザーIDに基づいてユーザーの詳細情報を取得します",
response_description="ユーザー情報オブジェクト",
tags=["ユーザー管理"]
)
async def get_user(
user_id: int = Path(..., title="ユーザーID", description="取得するユーザーID", ge=1),
include_posts: bool = Query(False, title="記事を含む", description="ユーザーの記事リストを含めるかどうか")
):
"""
ユーザー情報を取得:
- **user_id**: ユーザーの一意の識別子
- **include_posts**: レスポンスにユーザーの記事リストを含めるかどうか
ユーザーの基本情報を返します。include_postsがTrueの場合は、記事リストも含まれます。
"""
user = find_user(user_id)
if include_posts:
user.posts = get_user_posts(user_id)
return user
# カスタムOpenAPIスキーマ
def custom_openapi():
if app.openapi_schema:
return app.openapi_schema
openapi_schema = get_openapi(
title="カスタムAPIドキュメント",
version="2.5.0",
description="これはカスタムのOpenAPIスキーマです",
routes=app.routes,
)
# カスタム情報を追加
openapi_schema["info"]["x-logo"] = {
"url": "https://example.com/logo.png"
}
app.openapi_schema = openapi_schema
return app.openapi_schema
app.openapi = custom_openapi
依存性注入システムのプレビュー
例
from fastapi import Depends
# 単純な依存関係
def get_current_user_id() -> int:
# トークンからユーザーIDを解析
return 123
def get_database_session():
# データベースセッションを作成
db = DatabaseSession()
try:
yield db
finally:
db.close()
# 依存関係を使用
@app.get("/profile")
async def get_profile(
user_id: int = Depends(get_current_user_id),
db = Depends(get_database_session)
):
return get_user_profile(db, user_id)
# 依存関係チェーン
def get_current_user(
user_id: int = Depends(get_current_user_id),
db = Depends(get_database_session)
):
return db.query(User).filter(User.id == user_id).first()
@app.get("/dashboard")
async def get_dashboard(
current_user: User = Depends(get_current_user) # 他の依存関係に依存
):
return generate_dashboard(current_user)
# 単純な依存関係
def get_current_user_id() -> int:
# トークンからユーザーIDを解析
return 123
def get_database_session():
# データベースセッションを作成
db = DatabaseSession()
try:
yield db
finally:
db.close()
# 依存関係を使用
@app.get("/profile")
async def get_profile(
user_id: int = Depends(get_current_user_id),
db = Depends(get_database_session)
):
return get_user_profile(db, user_id)
# 依存関係チェーン
def get_current_user(
user_id: int = Depends(get_current_user_id),
db = Depends(get_database_session)
):
return db.query(User).filter(User.id == user_id).first()
@app.get("/dashboard")
async def get_dashboard(
current_user: User = Depends(get_current_user) # 他の依存関係に依存
):
return generate_dashboard(current_user)
型ヒントの重要性
例
from typing import List, Optional, Union, Dict, Any
from pydantic import BaseModel
# FastAPIは型ヒントに完全に依存して:
# 1. データ検証
# 2. ドキュメント生成
# 3. エディターサポート
@app.get("/items/{item_id}")
async def get_item(
item_id: int, # パスパラメータ、intに自動変換
q: Optional[str] = None, # オプションのクエリパラメータ
limit: int = 10 # デフォルト値を持つクエリパラメータ
) -> Dict[str, Any]: # 戻り値の型ヒント
"""型ヒントはFastAPIにパラメータとレスポンスの処理方法を指示します"""
return {"item_id": item_id, "q": q, "limit": limit}
# 複雑な型ヒント
@app.post("/items/")
async def create_items(
items: List[ItemCreate] # ItemCreateオブジェクトのリストを受け取る
) -> List[ItemResponse]: # ItemResponseオブジェクトのリストを返す
return [create_item(item) for item in items]
# Union型(複数の可能な型)
@app.get("/search")
async def search(
q: str,
result_type: str = "json"
) -> Union[List[Dict], str]: # 辞書のリストまたは文字列を返すことができる
if result_type == "json":
return [{"title": "結果1"}, {"title": "結果2"}]
else:
return "結果1, 結果2"
from pydantic import BaseModel
# FastAPIは型ヒントに完全に依存して:
# 1. データ検証
# 2. ドキュメント生成
# 3. エディターサポート
@app.get("/items/{item_id}")
async def get_item(
item_id: int, # パスパラメータ、intに自動変換
q: Optional[str] = None, # オプションのクエリパラメータ
limit: int = 10 # デフォルト値を持つクエリパラメータ
) -> Dict[str, Any]: # 戻り値の型ヒント
"""型ヒントはFastAPIにパラメータとレスポンスの処理方法を指示します"""
return {"item_id": item_id, "q": q, "limit": limit}
# 複雑な型ヒント
@app.post("/items/")
async def create_items(
items: List[ItemCreate] # ItemCreateオブジェクトのリストを受け取る
) -> List[ItemResponse]: # ItemResponseオブジェクトのリストを返す
return [create_item(item) for item in items]
# Union型(複数の可能な型)
@app.get("/search")
async def search(
q: str,
result_type: str = "json"
) -> Union[List[Dict], str]: # 辞書のリストまたは文字列を返すことができる
if result_type == "json":
return [{"title": "結果1"}, {"title": "結果2"}]
else:
return "結果1, 結果2"
中核概念の実践例
例
from fastapi import FastAPI, HTTPException, status, Depends, Query
from pydantic import BaseModel, Field
from typing import List, Optional
from datetime import datetime
import asyncio
# 総合例:ブログAPI
app = FastAPI(
title="ブログAPI",
description="FastAPIの中核概念を示すブログシステム",
version="1.0.0"
)
# データモデル
class PostBase(BaseModel):
title: str = Field(..., min_length=1, max_length=200)
content: str = Field(..., min_length=1)
published: bool = Field(True)
class PostCreate(PostBase):
pass
class PostResponse(PostBase):
id: int
author_id: int
created_at: datetime
updated_at: Optional[datetime] = None
class Config:
orm_mode = True
# モックデータベース
posts_db = []
next_id = 1
# 依存関係:現在のユーザーを取得(簡易版)
async def get_current_user() -> int:
# 実際のアプリケーションではJWTトークンから解析します
return 1
# 非同期パス操作
@app.get("/posts", response_model=List[PostResponse], tags=["記事"])
async def list_posts(
skip: int = Query(0, ge=0, description="スキップする記事数"),
limit: int = Query(10, ge=1, le=100, description="返す記事数"),
published_only: bool = Query(True, description="公開済みの記事のみを返す")
):
"""
記事リストを取得
ページネーションとフィルタリング機能をサポート
"""
# 非同期データベースクエリをモックする
await asyncio.sleep(0.1)
filtered_posts = posts_db
if published_only:
filtered_posts = [p for p in posts_db if p["published"]]
return filtered_posts[skip:skip + limit]
@app.post("/posts", response_model=PostResponse, status_code=status.HTTP_201_CREATED, tags=["記事"])
async def create_post(
post: PostCreate,
current_user_id: int = Depends(get_current_user)
):
"""
新しい記事を作成
ユーザー認証が必要
"""
global next_id
# 非同期データベース操作をモックする
await asyncio.sleep(0.1)
new_post = {
"id": next_id,
"title": post.title,
"content": post.content,
"published": post.published,
"author_id": current_user_id,
"created_at": datetime.now(),
"updated_at": None
}
posts_db.append(new_post)
next_id += 1
return new_post
@app.get("/posts/{post_id}", response_model=PostResponse, tags=["記事"])
async def get_post(post_id: int):
"""
特定の記事を取得
記事IDに基づいて記事の詳細を返す
"""
# 非同期データベースクエリをモックする
await asyncio.sleep(0.1)
post = next((p for p in posts_db if p["id"] == post_id), None)
if not post:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Post with id {post_id} not found"
)
return post
# ヘルスチェックエンドポイント
@app.get("/health", tags=["システム"])
async def health_check():
"""システムヘルスチェック"""
return {
"status": "healthy",
"timestamp": datetime.now(),
"posts_count": len(posts_db)
}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
from pydantic import BaseModel, Field
from typing import List, Optional
from datetime import datetime
import asyncio
# 総合例:ブログAPI
app = FastAPI(
title="ブログAPI",
description="FastAPIの中核概念を示すブログシステム",
version="1.0.0"
)
# データモデル
class PostBase(BaseModel):
title: str = Field(..., min_length=1, max_length=200)
content: str = Field(..., min_length=1)
published: bool = Field(True)
class PostCreate(PostBase):
pass
class PostResponse(PostBase):
id: int
author_id: int
created_at: datetime
updated_at: Optional[datetime] = None
class Config:
orm_mode = True
# モックデータベース
posts_db = []
next_id = 1
# 依存関係:現在のユーザーを取得(簡易版)
async def get_current_user() -> int:
# 実際のアプリケーションではJWTトークンから解析します
return 1
# 非同期パス操作
@app.get("/posts", response_model=List[PostResponse], tags=["記事"])
async def list_posts(
skip: int = Query(0, ge=0, description="スキップする記事数"),
limit: int = Query(10, ge=1, le=100, description="返す記事数"),
published_only: bool = Query(True, description="公開済みの記事のみを返す")
):
"""
記事リストを取得
ページネーションとフィルタリング機能をサポート
"""
# 非同期データベースクエリをモックする
await asyncio.sleep(0.1)
filtered_posts = posts_db
if published_only:
filtered_posts = [p for p in posts_db if p["published"]]
return filtered_posts[skip:skip + limit]
@app.post("/posts", response_model=PostResponse, status_code=status.HTTP_201_CREATED, tags=["記事"])
async def create_post(
post: PostCreate,
current_user_id: int = Depends(get_current_user)
):
"""
新しい記事を作成
ユーザー認証が必要
"""
global next_id
# 非同期データベース操作をモックする
await asyncio.sleep(0.1)
new_post = {
"id": next_id,
"title": post.title,
"content": post.content,
"published": post.published,
"author_id": current_user_id,
"created_at": datetime.now(),
"updated_at": None
}
posts_db.append(new_post)
next_id += 1
return new_post
@app.get("/posts/{post_id}", response_model=PostResponse, tags=["記事"])
async def get_post(post_id: int):
"""
特定の記事を取得
記事IDに基づいて記事の詳細を返す
"""
# 非同期データベースクエリをモックする
await asyncio.sleep(0.1)
post = next((p for p in posts_db if p["id"] == post_id), None)
if not post:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Post with id {post_id} not found"
)
return post
# ヘルスチェックエンドポイント
@app.get("/health", tags=["システム"])
async def health_check():
"""システムヘルスチェック"""
return {
"status": "healthy",
"timestamp": datetime.now(),
"posts_count": len(posts_db)
}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)