1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

API GatewayとLambdaでREST APIを作ってみる

Posted at

こんにちは。
株式会社クラスアクト インフラストラクチャ事業部の大塚です。

今回はAPI GatewayとLambdaを使用して、本当に簡単なREST API環境を用意してみたいと思います。

環境イメージ

growi-ページ33.drawio.png

REST APIとは?

AIより

REST(Representational State Transfer)に基づいたAPIで、HTTPプロトコルを利用してリソースにアクセスします。URLを通じてリソースを表現し、HTTPメソッド(GET、POST、PUT、DELETEなど)を使用して操作します。

構築

Lambda関数から作っていきます。
今回は以下の設定で作りました。名前はHello-REST-API、ランタイムはPython 3.13にしました。
screencapture-ap-northeast-1-console-aws-amazon-lambda-home-2025-05-04-16_19_20.png
作成後、コードタブのlambda_function.pyを次のように修正します。

lambda_function.py
import json

def lambda_handler(event, context):
    # "Hello AWS API Gateway!"というメッセージを返す
    response = {
        'statusCode': 200,
        'body': json.dumps({'message': 'Hello AWS API Gateway!'})
    }
    
    return response

修正が完了したら、Deployを押下して設定を反映します。
image.png

次にAPIゲートウェイの管理画面にアクセス
APIの作成を押下します。
image (1).png

REST APIの構築を押下します。
screencapture-ap-northeast-1-console-aws-amazon-apigateway-main-precreate-2025-05-04-19_21_54.png

以下の設定で作成を実行します。HelloAPIという名前で今回は作成しました。
image (2).png

作成が終わると以下のような画面が表示されます。
リソースを作成ボタンを押下して設定を入れ込んでいきます。
image (3).png

リソース名のところにhelloと入力してリソースを作成を押下します。
image (4).png

hellが表示されていることを確認します。
この状態でメソッドを作成を押下します。
image (5).png

メソッドはPOST、投稿タイプはLambda、関数は先ほど作成したものを選択してメソッドを作成を押下します。
screencapture-ap-northeast-1-console-aws-amazon-apigateway-main-apis-5bg8f5nwy2-resources-tpnzd3-create-method-2025-05-04-19_32_02 (1).png

画面が以下のように変化します。
image (6).png

テストタブのテストボタンを押下すると、実際にAPIを叩くことが出来ます。
ステータスが200でレスポンスもしっかり帰ってきているように見えます。
確認出来たらAPIをデプロイを押下します。
screencapture-ap-northeast-1-console-aws-amazon-apigateway-main-apis-5bg8f5nwy2-resources-2025-05-04-19_54_59.png

新しいステージで、devと名前を付けてデプロイしていきます。
image (7).png

デプロイ出来たら、URLを呼び出すところに記載されているURLを控えます。
image (8).png

以下のようにcurlコマンドを叩きます。
反応がありますね!

C:\Users\ohtsu>curl -X POST https://5bg8f5nwy2.execute-api.ap-northeast-1.amazonaws.com/dev/hello
{"statusCode": 200, "body": "{\"message\": \"Hello AWS API Gateway!\"}"}
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?