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?

SAMをインストールする

1
Posted at

サーバーレスなページを作ってみたいということで、まずは環境構築(AWS Configure)は既に入っているものとする。

sudo apt update

# 2. 必要なツールをインストール
sudo apt install -y curl unzip build-essential

curl -L https://github.com/aws/aws-sam-cli/releases/latest/download/aws-sam-cli-linux-x86_64.zip -o aws-sam-cli.zip

unzip aws-sam-cli.zip -d sam-installation

sudo ./sam-installation/install --update

sam --version

sam init --name my-first-api
cd my-first-api

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

Resources:
  MyApi:
    Type: AWS::Serverless::HttpApi
    Properties:
      StageName: Prod          # ← Prodに統一(大事!)
      CorsConfiguration:
        AllowOrigins: ["*"]
        AllowMethods: [GET, POST, PUT, DELETE, OPTIONS]

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

      Events:
        HelloEvent:
          Type: HttpApi
          Properties:
            ApiId: !Ref MyApi
            Path: /hello           # ← これで /hello にアクセス可能に
            Method: ANY

        RootEvent:                 # ルートも念のため
          Type: HttpApi
          Properties:
            ApiId: !Ref MyApi
            Path: /
            Method: ANY
app.py
import json

def lambda_handler(event, context):
    return {
        "statusCode": 200,
        "headers": {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "*"
        },
        "body": json.dumps({
            "message": "こんにちは!API Gateway付きで動いています🎉",
            "path": event.get("rawPath", "不明")
        })
    }
sam build
sam deploy --guided

こんにちは!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?