2
0

More than 1 year has passed since last update.

Mangumを用いたFastAPI製APIのSAM Local実行方法 メモ

Posted at
  • Fast APIで作成したAPIをSAM Localで実行する方法についてメモする。

Mangum

  • ASGI(Asynchronous Server Gateway Interface)アプリをAWS Lambdaで動作させるためのアダプター
  • FastAPIなどで実装したASGIアプリを、Lambda + API Gateway構成でサーバレスにWebアプリケーションとして動かす事が可能
  • FastAPI利用者であれば、Lambda特有の文法を覚えずLambda利用をスモールスタートできる

手順

1.サンプルSAMプロジェクトを作成

sam init

※ランタイムはPython3.8を選択

  • `template.yml

    • Hello World Exampleを利用する。
    • 特に内容は変更しない。
  • requirements.txt

  requests
  mangum
  uvicorn
  fastapi

※Mangum,FastAPIを利用するためのライブラリを追加

2.サンプルFastAPIアプリ用意

  • asgi_app.py
    • {project_dir}/hello_worldディレクトリに配置
from fastapi import FastAPI

app = FastAPI()

@app.get("/hello")
def root():
    return {"message": "Hello World"}

3.Lambdaハンドラ修正

  • app.py
from mangum import Mangum
from asgi_app import app

lambda_handler = Mangum(app)

動作確認

1.ビルド

sam build --use-container

2.起動

sam local start-api

3.リクエスト

GET /hello HTTP/1.1
Host: 127.0.0.1:3000

4.レスポンス

Status: 200 OK
{
    "message": "Hello World"
}

参考情報

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0