restapi について
Golden Armada AI Agent Fleet Platform 向けの REST API 設計・実装スキルです。エンドポイントの規約、FastAPI の例、認証、エラー処理、テスト、OpenAPI ドキュメントを扱います。
主な機能
- 01リソース命名と HTTP メソッド
- 02FastAPI のエンドポイント例
- 03JWT と API キー認証
- 04エラーレスポンス処理
- 05curl による API テスト
- 06OpenAPI ドキュメント設定
活用シーン
- 01Agent 向け REST エンドポイントの設計
- 02認証付き API ルートの実装
- 03API エラーとステータスコードの統一
- 04curl でリクエストをテスト
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ thelobbi/ claude --skill restapiインストール後、Claude Code で/restapiを入力して読み込まれたか確認します。
詳細
REST API スキル
Golden Armada AI Agent Fleet Platform 向けに、REST API の設計と実装に関する包括的な機能を提供します。
このスキルを使用する場面
次の作業を行う際に、このスキルを有効にしてください。
- API エンドポイントの設計
- HTTP リクエスト/レスポンスの処理
- API 認証
- OpenAPI ドキュメント
- API テスト
REST API 設計の原則
リソースの命名
```
推奨 - 名詞、複数形
GET /agents GET /agents/{id} POST /agents PUT /agents/{id} DELETE /agents/{id}
ネストされたリソース
GET /agents/{id}/tasks POST /agents/{id}/tasks
非推奨 - 動詞、アクション
GET /getAgents POST /createAgent ```
HTTP メソッド
| メソッド | 用途 | 冪等性 |
|---|---|---|
| GET | リソースの読み取り | あり |
| POST | リソースの作成 | なし |
| PUT | リソースの置き換え | あり |
| PATCH | 部分更新 | なし |
| DELETE | リソースの削除 | あり |
ステータスコード
```
成功
200 OK - GET、PUT、PATCH の成功 201 Created - POST の成功 204 No Content - DELETE の成功
クライアントエラー
400 Bad Request - 検証エラー 401 Unauthorized - 認証が必要です 403 Forbidden - 許可されていません 404 Not Found - リソースが見つかりません 409 Conflict - 重複/競合 422 Unprocessable - 意味的な検証エラー
サーバーエラー
500 Internal Error - サーバーエラー 502 Bad Gateway - アップストリームエラー 503 Service Unavailable - 一時的な過負荷 ```
API の実装(FastAPI)
```python from fastapi import FastAPI, HTTPException, Query, Path, Depends, status from typing import List, Optional from pydantic import BaseModel, Field
app = FastAPI(title="Golden Armada API", version="1.0.0")
モデル
class AgentCreate(BaseModel): name: str = Field(..., min_length=1, max_length=100) type: str = Field(..., pattern="^(claude|gpt|gemini)$")
class AgentResponse(BaseModel): id: str name: str type: str status: str created_at: datetime
エンドポイント
@app.get("/agents", response_model=List[AgentResponse]) async def list_agents( skip: int = Query(0, ge=0), limit: int = Query(100, ge=1, le=1000), status: Optional[str] = Query(None) ): """ページネーションとフィルタリングを適用して、すべてのエージェントを一覧表示します。""" return await agent_service.list(skip=skip, limit=limit, status=status)
@app.get("/agents/{agent_id}", response_model=AgentResponse) async def get_agent(agent_id: str = Path(..., description="エージェント ID")): """ID を指定して特定のエージェントを取得します。""" agent = await agent_service.get(agent_id) if not agent: raise HTTPException(status_code=404, detail="エージェントが見つかりません") return agent
@app.post("/agents", response_model=AgentResponse, status_code=201) async def create_agent(agent: AgentCreate): """新しいエージェントを作成します。""" return await agent_service.create(agent)
@app.put("/agents/{agent_id}", response_model=AgentResponse) async def update_agent(agent_id: str, agent: AgentCreate): """既存のエージェントを置き換えます。""" existing = await agent_service.get(agent_id) if not existing: raise HTTPException(status_code=404, detail="エージェントが見つかりません") return await agent_service.update(agent_id, agent)
@app.delete("/agents/{agent_id}", status_code=204) async def delete_agent(agent_id: str): """エージェントを削除します。""" deleted = await agent_service.delete(agent_id) if not deleted: raise HTTPException(status_code=404, detail="エージェントが見つかりません") ```
認証
JWT 認証
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
async def get_current_user(token: str = Depends(oauth2_scheme)):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
user_id: str = payload.get("sub")
if user_id is None:
raise credentials_exception
except JWTError:
raise credentials_exception
return await get_user(user_id)
# 保護されたエンドポイント
@app.get("/protected")
async def protected_route(user: User = Depends(get_current_user)):
return {"user": user.email}
API キー認証
from fastapi.security import APIKeyHeader
api_key_header = APIKeyHeader(name="X-API-Key")
async def verify_api_key(api_key: str = Depends(api_key_header)):
if api_key != VALID_API_KEY:
raise HTTPException(status_code=403, detail="Invalid API key")
return api_key
エラー処理
class ErrorResponse(BaseModel):
error: str
message: str
details: Optional[dict] = None
@app.exception_handler(ValueError)
async def value_error_handler(request, exc):
return JSONResponse(
status_code=400,
content=ErrorResponse(
error="validation_error",
message=str(exc)
).dict()
)
@app.exception_handler(Exception)
async def general_exception_handler(request, exc):
return JSONResponse(
status_code=500,
content=ErrorResponse(
error="internal_error",
message="An unexpected error occurred"
).dict()
)
curl による API テスト
# GET
curl -X GET "http://localhost:8000/agents" \
-H "Authorization: Bearer TOKEN"
# POST
curl -X POST "http://localhost:8000/agents" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer TOKEN" \
-d '{"name": "agent-1", "type": "claude"}'
# PUT
curl -X PUT "http://localhost:8000/agents/123" \
-H "Content-Type: application/json" \
-d '{"name": "updated-agent", "type": "claude"}'
# DELETE
curl -X DELETE "http://localhost:8000/agents/123" \
-H "Authorization: Bearer TOKEN"
OpenAPI ドキュメント
from fastapi import FastAPI
app = FastAPI(
title="Golden Armada API",
description="AI Agent Fleet Platform API",
version="1.0.0",
docs_url="/docs",
redoc_url="/redoc",
openapi_url="/openapi.json"
)
# ドキュメントへのアクセス先:
# - Swagger UI: http://localhost:8000/docs
# - ReDoc: http://localhost:8000/redoc
# - OpenAPI JSON: http://localhost:8000/openapi.json