[レポート]「API Gateway Unleashed: A Hands-on Journey to API Excellence」というセッションに参加しました #API303 #AWSreInvent

[レポート]「API Gateway Unleashed: A Hands-on Journey to API Excellence」というセッションに参加しました #API303 #AWSreInvent

2025.12.08

セッション概要

タイトル

API Gateway Unleashed: A Hands-on Journey to API Excellence
1

概要

In this hands-on workshop, gain essential skills to create, deploy, and manage APIs efficiently. Learn high-level concepts like message transformation, request validation, and security. Master deploying APIs using Infrastructure as Code and integrating with AWS Serverless services. Dive into monitoring and debugging to ensure your APIs perform optimally. Additionally, explore building and testing WebSocket backends. This session will equip you with the knowledge to streamline your application development and enhance API management. You must bring your laptop to participate.

Infrastructure as Code (IaC) や AWS サーバーレスサービスとの統合について解説します。API のパフォーマンスを最大限に引き出すためのモニタリングやデバッグ手法についても深く掘り下げ、さらに WebSocket バックエンドの構築とテストについても学びます。本セッションを通じて、アプリケーション開発の効率化や API 管理の強化に必要な知識を習得することができます。

スピーカー

  • Peterson Larentis, Specialist Solutions Architect Leader, LATAM, AWS
  • Eduardo Rodrigues, Principal Solutions Architect, Amazon Web Services

セッション情報

  • Type: Workshop
  • Level: 300
  • Topic: Application Integration, Business Applications

セッションで学んだこと

以下のようなサービスを連携させることでREST APIを構築していきます
archi

API Gatewayの活用

  • API GatewayからLambdaへのメッセージ変換(逆パターンも)
  • リクエスト検証
  • セキュリティ

Infrastructure as Code (IaC)の活用

  • IaCを使用したAPIのデプロイ方法
  • AWS Serverlessサービスとの統合

モニタリングとデバッグ

  • APIのパフォーマンス最適化
  • 監視とトラブルシューティング

セッションを受けてから作ってみたリソース

※Cognitoは今回省きます。API GatewayからLambdaの連携というスコープにしました。

CloudFormationのテンプレートファイル

template.yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  Sample SAM Template for BMI Calculator API

Globals:
    # Enable Logs
    Api:
        MethodSettings:
            - ResourcePath: "/*"
              HttpMethod: "*"
              DataTraceEnabled: True
              LoggingLevel: INFO
              MetricsEnabled: True
    Function:
        Timeout: 3
        Runtime: nodejs18.x

Resources:

    # REST API
    BmiAPI:
        Type: AWS::Serverless::Api
        Properties:
            StageName: dev
            OpenApiVersion: 3.0.3
            DefinitionBody:
                "Fn::Transform":
                    Name: "AWS::Include"
                    Parameters:
                        Location: "s3://technical-review/openapi.yaml" # 任意の場所に置く
            EndpointConfiguration:
                Type: REGIONAL

    # Lambda functions
    BmiCalculator:
        Type: AWS::Serverless::Function
        Properties:
            CodeUri: s3://technical-review/lambda/source.zip # 任意の場所に置く
            Handler: bmi-calculator.BmiCalculator

    # Execution Role
    LambdaExecutionRole:
        Type: AWS::IAM::Role
        Properties:
            AssumeRolePolicyDocument:
                Version: "2012-10-17"
                Statement:
                  - Effect: Allow
                    Principal:
                      Service:
                        - apigateway.amazonaws.com
                    Action:
                      - 'sts:AssumeRole'
            Policies:
                - PolicyName: AllowLambdaExec
                  PolicyDocument:
                    Version: "2012-10-17"
                    Statement:
                      - Effect: Allow
                        Action: 'lambda:InvokeFunction'
                        Resource: !GetAtt BmiCalculator.Arn

Outputs:
  BmiAPI:
    Description: "API Gateway endpoint URL for BMI Calculator API"
    Value: !Sub "https://${BmiAPI}.execute-api.${AWS::Region}.amazonaws.com/dev/"

OpenAPI形式のAPI仕様書

openapi.yaml
openapi: "3.0.1"
info:
   title: "bmi-calculator-api"
   description: "BMI Calculator API with IaC example"
   version: "1.0"

paths:

    /bmi:
        post:
            consumes:
            - "application/json"
            produces:
            - "application/json"
            responses:
                "200":
                    description: "200 response"
            x-amazon-apigateway-integration:
                httpMethod: "POST"
                credentials:
                    Fn::GetAtt: [LambdaExecutionRole, Arn]
                uri:
                  Fn::Sub: "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${BmiCalculator.Arn}/invocations"
                responses:
                    default:
                        statusCode: "200"
                passthroughBehavior: "when_no_match"
                type: "aws"

Lambdaのソース

bmi-calcalator.js
/**
 * このファイルには、BMI計算APIで使用されるLambda関数のソースコードが含まれます
 */

  module.exports.BmiCalculator = async (event) => {
    try {
      // Check if event is null or undefined and throw an error if it is
      if (!event) {
        throw new Error('Event object is undefined or empty');
      }

      // Use optional chaining to set default values for properties that may not exist
      const { height, weight, unit } = event ?? {};

      // バリデーション: 必須パラメータチェック
      if (!height || !weight) {
        throw new Error('Missing required parameters: height and weight');
      }

      // 数値変換とバリデーション
      const heightNum = parseFloat(height);
      const weightNum = parseFloat(weight);

      if (isNaN(heightNum) || isNaN(weightNum)) {
        throw new Error('Height and weight must be valid numbers');
      }

      if (heightNum <= 0 || weightNum <= 0) {
        throw new Error('Height and weight must be positive numbers');
      }

      // 身長をメートルに変換(デフォルトはcm)
      const heightInMeters = unit === 'm' ? heightNum : heightNum / 100;

      if (heightInMeters > 3.0 || heightInMeters < 0.5) {
        throw new Error('Height is out of valid range');
      }

      // BMI計算
      const bmi = (weightNum / (heightInMeters * heightInMeters)).toFixed(1);

      // BMIカテゴリー判定
      const category = getBmiCategory(parseFloat(bmi));

      // Return a response object with a 200 status code and JSON body
      const response = {
        statusCode: 200,
        body: JSON.stringify({
          bmi: bmi.toString(),
          category: category,
          height: heightNum,
          weight: weightNum,
          unit: unit || 'cm'
        }),
        headers: {
          'X-Powered-By': 'AWS API Gateway & Lambda Serverless'
        },
        isBase64Encoded: false
      };

      return response;
    } catch (error) {
      // Log the error and return a response object with a 400 status code and an error message
      console.error('Error calculating BMI:', error.message);
      return {
        statusCode: 400,
        body: 'Error calculating BMI',
        headers: {
          'X-Powered-By': 'AWS API Gateway & Lambda Serverless'
        },
        isBase64Encoded: false
      };
    }
  };

  // Define a helper function to determine BMI category
  function getBmiCategory(bmi) {
      if (bmi < 18.5) {
          return 'Underweight';
      } else if (bmi >= 18.5 && bmi < 25.0) {
          return 'Normal weight';
      } else if (bmi >= 25.0 && bmi < 30.0) {
          return 'Overweight';
      } else {
          return 'Obese';
      }
  }

動作確認

API Gatwayでテストやってみます。
0
結果を見てます。
1
API GatewayからLambdaにリクエストをしてBMIが計算されていることが確認できました。

さいごに

サーバーレスのサービスを組み合わせることで短時間でREST APIを公開できることが分かりました。また、単に作って終わりではなく計画から継続的な改善という循環プロセスであるということをきちんと理解した方がいいなと思いました。
2
ブログ公開時点で自分が参加したセッションの中で一番参加者の多いセッションでした。60席近くある椅子が全部埋まってました。
3

この記事をシェアする

FacebookHatena blogX

関連記事