ブログ(Claude Code) PR

Claude CodeでFastAPIエンドポイントを効率的に追加する方法

記事内に商品プロモーションを含む場合があります

Claude Codeを使ってFastAPIのエンドポイント開発を効率化する方法を解説。具体的なコード例とともに、CRUD操作、バリデーション、認証機能の実装まで、実務で使える開発手法を詳しく紹介します。AI支援による高品質なAPI開発を実現しましょう。

Claude CodeとFastAPI開発の相性について

Claude CodeはAI支援型の開発環境として注目されており、特にFastAPIのような現代的なWebフレームワークとの組み合わせで威力を発揮します。FastAPIは高性能なPython Webフレームワークであり、自動的なAPIドキュメント生成や型ヒントによる開発効率化が特徴です。
Claude Codeを活用することで、FastAPIのエンドポイント開発における以下の課題を解決できます:
– 繰り返し作業の自動化
– コード品質の向上
– セキュリティ対策の実装
– テストコードの自動生成
– ドキュメント作成の効率化
これらの機能を組み合わせることで、従来の手動開発と比較して開発速度を大幅に向上させることが可能です。

基本的なエンドポイント追加の手順

基本的なエンドポイント追加の手順

プロジェクト構造の準備

Claude Codeでは、まずプロジェクト構造を明確に定義することが重要です。FastAPIプロジェクトの標準的な構造を以下のように設定します:

project/
├── app/
│   ├── __init__.py
│   ├── main.py
│   ├── models/
│   │   ├── __init__.py
│   │   └── user.py
│   ├── routers/
│   │   ├── __init__.py
│   │   └── users.py
│   ├── schemas/
│   │   ├── __init__.py
│   │   └── user.py
│   └── database.py
└── requirements.txt

メインアプリケーションの設定

Claude Codeを使用してmain.pyファイルを作成し、基本的なFastAPIアプリケーションを設定します:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.routers import users
app = FastAPI(
title="My API",
description="Claude Codeで開発したAPI",
version="1.0.0"
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(users.router, prefix="/users", tags=["users"])
@app.get("/")
async def root():
return {"message": "Hello World"}

データモデルの定義

Claude Codeの支援により、Pydanticモデルを効率的に作成できます。schemas/user.pyファイルでユーザー関連のスキーマを定義します:

from pydantic import BaseModel, EmailStr, Field
from typing import Optional
from datetime import datetime
class UserBase(BaseModel):
email: EmailStr
username: str = Field(..., min_length=3, max_length=50)
full_name: Optional[str] = None
class UserCreate(UserBase):
password: str = Field(..., min_length=6)
class UserUpdate(BaseModel):
email: Optional[EmailStr] = None
username: Optional[str] = Field(None, min_length=3, max_length=50)
full_name: Optional[str] = None
class UserResponse(UserBase):
id: int
is_active: bool
created_at: datetime
updated_at: Optional[datetime] = None
class Config:
orm_mode = True

CRUD操作エンドポイントの実装

ユーザー作成エンドポイント

Claude Codeを活用して、セキュアなユーザー作成エンドポイントを実装します:

from fastapi import APIRouter, HTTPException, Depends, status
from sqlalchemy.orm import Session
from app.schemas.user import UserCreate, UserResponse
from app.database import get_db
from app.models.user import User
from passlib.context import CryptContext
router = APIRouter()
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def hash_password(password: str) -> str:
return pwd_context.hash(password)
@router.post("/", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
async def create_user(user: UserCreate, db: Session = Depends(get_db)):
# メールアドレスの重複チェック
db_user = db.query(User).filter(User.email == user.email).first()
if db_user:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Email already registered"
)
# ユーザー名の重複チェック
db_user = db.query(User).filter(User.username == user.username).first()
if db_user:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Username already taken"
)
# パスワードのハッシュ化
hashed_password = hash_password(user.password)
# ユーザーの作成
db_user = User(
email=user.email,
username=user.username,
full_name=user.full_name,
hashed_password=hashed_password
)
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user

ユーザー取得エンドポイント

Claude Codeの支援により、効率的なクエリとエラーハンドリングを含むエンドポイントを作成します:

@router.get("/{user_id}", response_model=UserResponse)
async def get_user(user_id: int, db: Session = Depends(get_db)):
db_user = db.query(User).filter(User.id == user_id).first()
if db_user is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="User not found"
)
return db_user
@router.get("/", response_model=List[UserResponse])
async def get_users(
skip: int = Query(0, ge=0),
limit: int = Query(100, ge=1, le=100),
db: Session = Depends(get_db)
):
users = db.query(User).offset(skip).limit(limit).all()
return users

ユーザー更新エンドポイント

Claude Codeを使用して、部分更新に対応したエンドポイントを実装します:

@router.put("/{user_id}", response_model=UserResponse)
async def update_user(
user_id: int,
user_update: UserUpdate,
db: Session = Depends(get_db)
):
db_user = db.query(User).filter(User.id == user_id).first()
if db_user is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="User not found"
)
update_data = user_update.dict(exclude_unset=True)
# メールアドレスの重複チェック(変更される場合)
if "email" in update_data:
existing_user = db.query(User).filter(
User.email == update_data["email"],
User.id != user_id
).first()
if existing_user:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Email already registered"
)
for field, value in update_data.items():
setattr(db_user, field, value)
db_user.updated_at = datetime.utcnow()
db.commit()
db.refresh(db_user)
return db_user
認証機能付きエンドポイントの実装

認証機能付きエンドポイントの実装

JWT認証の設定

Claude Codeを活用して、セキュアなJWT認証システムを構築します:

from jose import JWTError, jwt
from datetime import datetime, timedelta
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
SECRET_KEY = "your-secret-key-here"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
security = HTTPBearer()
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
async def get_current_user(
credentials: HTTPAuthorizationCredentials = Depends(security),
db: Session = Depends(get_db)
):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(credentials.credentials, SECRET_KEY, algorithms=[ALGORITHM])
user_id: int = payload.get("sub")
if user_id is None:
raise credentials_exception
except JWTError:
raise credentials_exception
user = db.query(User).filter(User.id == user_id).first()
if user is None:
raise credentials_exception
return user

ログインエンドポイント

@router.post("/login")
async def login(
form_data: OAuth2PasswordRequestForm = Depends(),
db: Session = Depends(get_db)
):
user = authenticate_user(db, form_data.username, form_data.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": str(user.id)}, expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}
def authenticate_user(db: Session, username: str, password: str):
user = db.query(User).filter(User.username == username).first()
if not user or not pwd_context.verify(password, user.hashed_password):
return False
return user

保護されたエンドポイント

@router.get("/profile", response_model=UserResponse)
async def get_profile(current_user: User = Depends(get_current_user)):
return current_user
@router.delete("/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_user(
user_id: int,
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db)
):
# 管理者権限の確認または自分のアカウントの削除のみ許可
if current_user.id != user_id and not current_user.is_admin:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Not enough permissions"
)
db_user = db.query(User).filter(User.id == user_id).first()
if db_user is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="User not found"
)
db.delete(db_user)
db.commit()

エラーハンドリングとバリデーション

Claude Codeを使用して、堅牢なエラーハンドリング機能を実装します:

from fastapi import Request
from fastapi.responses import JSONResponse
@app.exception_handler(ValueError)
async def value_error_handler(request: Request, exc: ValueError):
return JSONResponse(
status_code=400,
content={"message": "Invalid value", "detail": str(exc)}
)
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
return JSONResponse(
status_code=exc.status_code,
content={"message": exc.detail}
)
テストの自動生成

テストの自動生成

Claude Codeはテストコードの生成も支援します:

import pytest
from fastapi.testclient import TestClient
from app.main import app
client = TestClient(app)
def test_create_user():
response = client.post(
"/users/",
json={
"email": "test@example.com",
"username": "testuser",
"password": "testpass123"
}
)
assert response.status_code == 201
data = response.json()
assert data["email"] == "test@example.com"
assert data["username"] == "testuser"
def test_get_user():
response = client.get("/users/1")
assert response.status_code == 200

パフォーマンス最適化

Claude Codeを活用して、高性能なエンドポイントを作成するための最適化手法:

非同期処理の実装

import asyncio
from typing import List
@router.get("/users/bulk", response_model=List[UserResponse])
async def get_users_bulk(
user_ids: List[int],
db: Session = Depends(get_db)
):
async def get_user_async(user_id: int):
return db.query(User).filter(User.id == user_id).first()
tasks = [get_user_async(user_id) for user_id in user_ids]
users = await asyncio.gather(*tasks)
return [user for user in users if user is not None]
まとめ

まとめ

Claude CodeとFastAPIの組み合わせにより、効率的で高品質なAPI開発が可能になります。AI支援による開発では、コード生成の速度向上だけでなく、セキュリティ対策やテスト実装なども自動化できるため、開発者はより創造的な作業に集中できます。
継続的なスキル向上のために、Claude Codeの新機能をキャッチアップし、FastAPIのベストプラクティスと組み合わせることで、さらなる開発効率の向上を図りましょう。

ABOUT ME
松本大輔
LIXILで磨いた「クオリティーファースト」の哲学とAIの可能性への情熱を兼ね備えた経営者。2022年の転身を経て、2025年1月にRe-BIRTH株式会社を創設。CEOとして革新的AIソリューション開発に取り組む一方、Re-HERO社COOとColorful School DAO代表も兼任。マーケティング、NFT、AIを融合した独自モデルで競合を凌駕し、「生み出す」と「復活させる」という使命のもと、新たな価値創造に挑戦している。

著書:
AI共存時代の人間革命
YouTube成功戦略ガイド
SNS完全攻略ガイド
AI活用術