0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

サーバレスでPOSTとGETをしてみる

0
Posted at

lambdaを使ってPostとgetができるようにする。

my-first-api/                  ← ここがルートフォルダ
├── template.yaml
├── hello_world/
│   └── app.py
├── index.html                 ← ← ← ここに置く!
├── samconfig.toml
└── ...
template.yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Resources:
  # ================== API Gateway ==================
  MyApi:
    Type: AWS::Serverless::HttpApi
    Properties:
      StageName: Prod
      CorsConfiguration:
        AllowOrigins:
          - "*"
        AllowMethods:
          - GET
          - POST
          - PUT
          - DELETE
          - OPTIONS
        AllowHeaders:
          - Content-Type
          - Authorization
          - X-Amz-Date
          - X-Api-Key
          - X-Amz-Security-Token
        AllowCredentials: false

  # ================== Lambda関数 ==================
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello_world/
      Handler: app.lambda_handler
      Runtime: python3.12
      Timeout: 10
      MemorySize: 128

      Environment:
        Variables:
          VERSION: "2026.05.10"   # 強制デプロイ用

      Events:
        HelloEvent:
          Type: HttpApi
          Properties:
            ApiId: !Ref MyApi
            Path: /hello
            Method: ANY

        RootEvent:
          Type: HttpApi
          Properties:
            ApiId: !Ref MyApi
            Path: /
            Method: ANY



app.py

import json

def lambda_handler(event, context):
    # CORSヘッダー
    headers = {
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
        "Access-Control-Allow-Headers": "Content-Type, Authorization"
    }

    method = event.get("requestContext", {}).get("http", {}).get("method", "GET")

    if method == "OPTIONS":
        return {"statusCode": 200, "headers": headers, "body": ""}

    if method == "GET":
        body = {"message": "GETでアクセス成功🎉", "method": "GET"}
    
    elif method == "POST":
        try:
            body_data = json.loads(event.get("body", "{}"))
            body = {
                "message": "POSTを受け取りました!",
                "received_data": body_data,
                "method": "POST"
            }
        except:
            body = {"error": "JSONのパースに失敗しました"}
    
    else:
        body = {"error": f"{method} は未対応です"}

    return {
        "statusCode": 200,
        "headers": headers,
        "body": json.dumps(body, ensure_ascii=False)
    }

python3 -m http.server 8000
を実行し

http://localhost:8000/index.html
でgetとpostができることを確認。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?