FastAPI 連携
サーバー側 FastAPI アプリケーションから APIFuse を呼び出します。
FastAPI 連携
サーバー上で実行される FastAPI route から APIFuse を使用します。APIFuse API キーはサーバー設定に保存し、受信リクエストデータと APIFuse response の両方を検証してください。
1. 型付きモデルを追加する
schema bundle の Pydantic model を使用するか、API リファレンスの operation schema に一致する model を定義します。
2. gateway を呼び出す
import os
import httpx
from fastapi import APIRouter, Response
router = APIRouter()
@router.post("/places")
async def places(input_payload: dict) -> dict | Response:
api_key = os.environ["APIFUSE_API_KEY"]
async with httpx.AsyncClient(timeout=15.0) as client:
response = await client.post(
"https://api.apifuse.com/v1/kakaomap/search",
headers={"Authorization": f"Bearer {api_key}"},
json=input_payload,
)
if response.status_code >= 400:
# すべての失敗を 1 つのステータスに潰さず、APIFuse のエラー判定を
# (ステータスと body のバイトのまま)伝えてください。HTTPException は
# body を {"detail": ...} の下に包み、code / retryable / source
# フィールドを隠してしまいます。詳細はエラーハンドリングガイドへ。
return Response(
content=response.content,
status_code=response.status_code,
# アップストリームの Content-Type に関わらず JSON として返し、
# 予期しない non-JSON body が same-origin HTML として描画されるのを
# 防ぎます。ガイドが依存するリトライ・相関ヘッダーは保持します。
media_type="application/json",
headers={
key: value
for key, value in {
"Retry-After": response.headers.get("retry-after"),
"X-Request-Id": response.headers.get("x-request-id"),
}.items()
if value is not None
},
)
return response.json()3. アプリケーションデータを返す
ブラウザまたはモバイルクライアントに返す前に、APIFuse response をプロダクトに必要なデータ形式に整えます。