API¶
API
¶
Bases: BaseRouterMixin
モダンな Lambda 用 API フレームワーク
Source code in lambapi/core.py
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 |
|
__init__(event, context, root_path='')
¶
Source code in lambapi/core.py
include_router(router, prefix='', tags=None)
¶
ルーターを追加
Source code in lambapi/core.py
add_middleware(middleware)
¶
enable_cors(origins='*', methods=None, headers=None, allow_credentials=False, max_age=None, expose_headers=None)
¶
CORS を有効にする
Parameters:
Name | Type | Description | Default |
---|---|---|---|
origins
|
Union[str, List[str]]
|
許可するオリジン('*' または具体的な URL) |
'*'
|
methods
|
Optional[List[str]]
|
許可する HTTP メソッド |
None
|
headers
|
Optional[List[str]]
|
許可するヘッダー |
None
|
allow_credentials
|
bool
|
認証情報の送信を許可するか |
False
|
max_age
|
Optional[int]
|
プリフライトリクエストのキャッシュ時間(秒) |
None
|
expose_headers
|
Optional[List[str]]
|
ブラウザに公開するレスポンスヘッダー |
None
|
Source code in lambapi/core.py
error_handler(exception_type)
¶
エラーハンドラーデコレータ
default_error_handler(handler_func)
¶
handle_request()
¶
メインのリクエスト処理
Source code in lambapi/core.py
lambapi のメインクラスです。すべての API 機能はこのクラスを通じて提供されます。
基本的な使用法¶
from lambapi import API, create_lambda_handler
def create_app(event, context):
app = API(event, context)
@app.get("/")
def hello():
return {"message": "Hello, World!"}
return app
lambda_handler = create_lambda_handler(create_app)
初期化¶
API(event, context)¶
Lambda から渡されるイベントとコンテキストで API インスタンスを初期化します。
パラメータ:
event
(Dict[str, Any]): Lambda イベントオブジェクトcontext
(Any): Lambda コンテキストオブジェクト
例:
def lambda_handler(event, context):
app = API(event, context)
# ルート定義...
return app.handle_request()
HTTP メソッドデコレータ¶
get(path, request_format=None, response_format=None, cors=None)¶
GET リクエストのエンドポイントを定義します。
パラメータ:
path
(str): エンドポイントのパス(デフォルト: "/")request_format
(Type, optional): リクエストのバリデーション用データクラスresponse_format
(Type, optional): レスポンスのバリデーション用データクラスcors
(Union[bool, CORSConfig, None]): CORS 設定
例:
@app.get("/")
def root():
return {"message": "Root endpoint"}
@app.get("/users/{user_id}")
def get_user(user_id: str):
return {"id": user_id, "name": f"User {user_id}"}
@app.get("/search")
def search(q: str = "", limit: int = 10):
return {"query": q, "results": [], "limit": limit}
post(path, request_format=None, response_format=None, cors=None)¶
POST リクエストのエンドポイントを定義します。
例:
@app.post("/users")
def create_user(request):
user_data = request.json()
return {"message": "User created", "user": user_data}
put(path, request_format=None, response_format=None, cors=None)¶
PUT リクエストのエンドポイントを定義します。
delete(path, request_format=None, response_format=None, cors=None)¶
DELETE リクエストのエンドポイントを定義します。
patch(path, request_format=None, response_format=None, cors=None)¶
PATCH リクエストのエンドポイントを定義します。
ルーター統合¶
include_router(router, prefix="", tags=None)¶
Router インスタンスを API に統合します。
パラメータ:
router
(Router): 統合する Router インスタンスprefix
(str): すべてのルートに追加するプレフィックスtags
(List[str], optional): ルートに付与するタグ
例:
from lambapi import Router
# ユーザー関連のルーター
user_router = Router(prefix="/users")
@user_router.get("/")
def list_users():
return {"users": []}
@user_router.get("/{id}")
def get_user(id: str):
return {"id": id}
# メインアプリに統合
app.include_router(user_router)
# /users/ と /users/{id} が利用可能になる
ミドルウェア¶
add_middleware(middleware)¶
ミドルウェア関数を追加します。
パラメータ:
middleware
(Callable): ミドルウェア関数
ミドルウェア関数のシグネチャ:
例:
def logging_middleware(request, response):
print(f"{request.method} {request.path}")
return response
def cors_middleware(request, response):
if isinstance(response, Response):
response.headers.update({
'Access-Control-Allow-Origin': '*'
})
return response
app.add_middleware(logging_middleware)
app.add_middleware(cors_middleware)
CORS 設定¶
enable_cors(origins="*", methods=None, headers=None, allow_credentials=False, max_age=None, expose_headers=None)¶
グローバル CORS 設定を有効にします。
パラメータ:
origins
(Union[str, List[str]]): 許可するオリジン(デフォルト: "*")methods
(List[str], optional): 許可する HTTP メソッドheaders
(List[str], optional): 許可するヘッダーallow_credentials
(bool): 認証情報の送信を許可(デフォルト: False)max_age
(int, optional): プリフライトキャッシュ時間(秒)expose_headers
(List[str], optional): ブラウザに公開するレスポンスヘッダー
例:
# 基本的な CORS 設定
app.enable_cors()
# 詳細な CORS 設定
app.enable_cors(
origins=["https://example.com", "https://app.example.com"],
methods=["GET", "POST", "PUT", "DELETE"],
headers=["Content-Type", "Authorization"],
allow_credentials=True,
max_age=3600
)
エラーハンドリング¶
error_handler(exception_type)¶
特定の例外タイプに対するカスタムエラーハンドラーを登録します。
パラメータ:
exception_type
(Type[Exception]): 処理する例外タイプ
例:
class BusinessError(Exception):
def __init__(self, message: str, code: str):
self.message = message
self.code = code
@app.error_handler(BusinessError)
def handle_business_error(error, request, context):
return Response({
"error": "BUSINESS_ERROR",
"message": error.message,
"code": error.code
}, status_code=422)
default_error_handler(handler_func)¶
すべての未処理例外に対するデフォルトエラーハンドラーを設定します。
例:
@app.default_error_handler
def handle_unknown_error(error, request, context):
return Response({
"error": "INTERNAL_ERROR",
"message": "An unexpected error occurred",
"request_id": context.aws_request_id
}, status_code=500)
リクエスト処理¶
handle_request()¶
メインのリクエスト処理メソッド。Lambda ハンドラーから呼び出されます。
戻り値:
Dict[str, Any]: Lambda レスポンス形式の辞書
例:
def lambda_handler(event, context):
app = API(event, context)
@app.get("/")
def hello():
return {"message": "Hello!"}
return app.handle_request()
バリデーション¶
リクエストバリデーション¶
request_format
パラメータを使用してリクエストボディを自動検証できます:
from dataclasses import dataclass
@dataclass
class CreateUserRequest:
name: str
email: str
age: int = 0
@app.post("/users", request_format=CreateUserRequest)
def create_user(request: CreateUserRequest):
# request は自動的に CreateUserRequest インスタンスに変換される
return {
"message": f"User {request.name} created",
"email": request.email
}
レスポンスバリデーション¶
response_format
パラメータを使用してレスポンスを自動検証できます:
@dataclass
class UserResponse:
id: str
name: str
email: str
@app.get("/users/{id}", response_format=UserResponse)
def get_user(id: str) -> UserResponse:
# 戻り値は UserResponse として検証される
return {
"id": id,
"name": f"User {id}",
"email": f"user{id}@example.com"
}
パラメータ注入¶
lambapi は関数シグネチャを解析して、自動的にパラメータを注入します:
パスパラメータ¶
@app.get("/users/{user_id}/posts/{post_id}")
def get_post(user_id: str, post_id: str):
return {"user_id": user_id, "post_id": post_id}
クエリパラメータ¶
@app.get("/items")
def get_items(limit: int = 10, offset: int = 0, active: bool = True):
return {
"limit": limit, # 自動的に int に変換
"offset": offset, # 自動的に int に変換
"active": active # 自動的に bool に変換
}
型変換¶
型注釈 | 変換動作 |
---|---|
str |
そのまま文字列 |
int |
int() で変換、失敗時は 0 |
float |
float() で変換、失敗時は 0.0 |
bool |
'true' , '1' , 'yes' , 'on' を True として認識 |
Request オブジェクトの使用¶
従来の方式で Request オブジェクトを直接使用することも可能です:
@app.post("/upload")
def upload_file(request):
# 全リクエスト情報にアクセス
content_type = request.headers.get("content-type")
body = request.body
method = request.method
path = request.path
return {"uploaded": True}
高度な使用例¶
条件付きルート¶
@app.get("/admin/users")
def admin_users(request):
# 認証チェック
auth_header = request.headers.get("authorization")
if not auth_header:
raise AuthenticationError("Authentication required")
return {"users": ["admin_user1", "admin_user2"]}
カスタムレスポンス¶
from lambapi import Response
@app.get("/download")
def download_file():
return Response(
"file content",
status_code=200,
headers={
"Content-Type": "application/octet-stream",
"Content-Disposition": "attachment; filename=file.txt"
}
)
非同期処理(シミュレート)¶
import time
@app.post("/process")
def start_processing(request):
# 非同期処理のシミュレート
task_id = f"task_{int(time.time())}"
return Response(
{"task_id": task_id, "status": "processing"},
status_code=202
)
関連項目¶
- Router - ルーターによるエンドポイントのグループ化
- Request - リクエストオブジェクトの詳細
- Response - レスポンスオブジェクトの詳細
- Exceptions - エラーハンドリングと例外クラス