0
1

FastAPIのAPIサーバをAWSのAPI Gateway+Lambdaを使って動作させる方法

Last updated at Posted at 2024-09-17

デプロイ手順

※FastAPIのアプリケーションがある

  1. LambdaでFastAPIのAPIサーバを実行できるようにする設定をする(Mangum
  2. Serverless FrameworkでAWSにデプロイできるようにする
    • LambdaにPythonライブラリがインストールされるようにする設定をする
  3. Serverless Framework でAWSにデプロイする

FastAPIのアプリケーションがある

app.py

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def hello_world():
    return {'message': 'Hello from FastAPI'}

LambdaでFastAPIのAPIサーバを実行できるようにする設定をする(Mangum)

  • Mangumは、AWS Lambda固有のイベントとFastAPIなどのASGIアプリの間のアダプタとして機能する
from fastapi import FastAPI
from mangum import Mangum

app = FastAPI()

@app.get("/")
def hello_world():
    return {'message': 'Hello from FastAPI'}

handler = Mangum(app)

Serverless FrameworkでAWSにデプロイできるようにする

  • LambdaにPythonライブラリがインストールされるようにserverless-python-requirements のプラグインを使う
  • Serverless Frameworkの設定ファイルを記述する

requirements.txt

※fastapiは新しいバージョンだとエラーになる

fastapi==0.99.0
mangum==0.17.0

serverless.yml

service: fastapi-apigateway-lambda
frameworkVersion: '4'

provider:
  name: aws
  runtime: python3.11

functions:
  api:
    handler: app.handler
    events:
      - httpApi: '*'

plugins:
  - serverless-python-requirements

package:
  exclude:
    - node_modules/**

Serverless Framework で AWSにデプロイする

  • serverless deploy
    ※IAM権限エラーの場合は、権限を付与する
serverless deploy

Deploying "fastapi-apigateway-lambda" to stage "dev" (us-east-1)

✔ Service deployed to stack fastapi-apigateway-lambda-dev (79s)

endpoint: ANY - https://xxxx.execute-api.us-east-1.amazonaws.com
functions:
  api: fastapi-apigateway-lambda-dev-api (6 MB)

デプロイ確認

  • APIエンドポイントへリクエスト
curl https://xxxx.execute-api.us-east-1.amazonaws.com
{"message":"Hello from FastAPI"}
  • AWSマネージメントコンソール
    • S3
    • CloudFormation ※ リソースタブから作成リソースを確認できる
    • Lambda
    • API Gateway
    • CloudWatch
    • IAM ロール

参考

0
1
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
0
1