1
0

API Gatewayで/{proxy+}メソッドを活用する方法

Last updated at Posted at 2023-12-01

はじめに

こんにちは、開発部の天津炒飯です。

CloudFormationのLambda Functionでパスごと、Eventsを一つずつ書くことで苦労した経験があるかもしれません。
API Gatewayの /{proxy+} メソッドを使用すると、異なるパスに対するルーティングを簡単に実現できますが、意外と日本語の情報が少ないです。
私はPythonのWebフレームワークであるFastAPIを使用したので、この記事ではFastAPIを使用してAPI Gatewayの /{proxy+} メソッドを活用する方法に焦点を当てます。

1. /{proxy+}メソッドとは

/{proxy+} メソッドは、ワイルドカードパスを表すもので、異なるパス構造のリクエストを同じAPIエンドポイントにルーティングするのに役立ちます。
例えば、 /products/{proxy+}/products/item1/products/category1/item2 など、様々なパスに対応できます。

2. /{proxy+}メソッドの設定

2.1 SAMテンプレートの作成

SAMを使用してFastAPIアプリケーションをデプロイするためのtemplate.yamlを作成します。Lambda関数、API Gatewayのリソース、および必要な設定を定義します。

そして、冒頭で述べた通り、各パスごとに Events を一つずつ記述するのではなく、 /{proxy+} メソッドを使用して、 ItemApi1 および ItemApi2MyApi にまとめて記述します。

template.yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Resources:
  MyApi:
    Type: AWS::Serverless::Api

  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: main.handler
      Runtime: python3.8
      CodeUri: ./path/to/your/fastapi/app
      Events:
-        ItemApi1:
-          Type: Api
-          Properties:
-            Path: /item1
-            Method: get
-        ItemApi2:
-          Type: Api
-          Properties:
-            Path: /category1/item2
-            Method: post
+        MyApi:
+          Type: Api
+          Properties:
+            Path: /{proxy+}
+            Method: any

2.2 FastAPIアプリケーションのLambdaへの統合

FastAPIアプリケーションをLambda関数に統合するために、Lambda関数内でFastAPIアプリケーションを呼び出します。

main.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/item1")
async def get_item():
    return "hello!"

@app.post("/category1/item2")
async def post_item():
    return "world!"
handler.py
from mangum import Mangum
from main import app

def handler(event, context):
    api_handler = Mangum(app)
    return api_handler(event, context)

3. デプロイ

CloudFormationスタックを作成し、API Gatewayの設定とLambda関数をデプロイします。

4. サンプルリクエスト

これで、API Gatewayで /{proxy+} メソッドが有効なAPIが作成されました。クライアントは任意のパスでリクエストを送信できます。
例えば、 /products/item1 にGETリクエストを送信すると、Lambda関数が対応する処理を実行します。

% GET https://your-api-url/products/item1
hello!

以上で、API Gatewayで /{proxy+} メソッドを使用する基本的な手順が完了しました。この柔軟なメソッドを使用することで、異なるパスへのリクエストを簡単に処理できます。

最後に

この記事では、FastAPIとSAMを使用して /{proxy+} メソッドを活用する基本的な手順を紹介しています。
FastAPIの具体的な実装やSAMの詳細な設定については、FastAPIおよびAWS SAMの公式ドキュメントを参照してください。

はつかぜ株式会社では、IT学習や業務に役立つ情報を定期的にお届けしていきたいと思っています。
システム開発のお問い合わせ・ご相談はこちら
https://www.hatsukaze.co.jp/inquire/

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