amazon-web-servicesaws-lambdaaws-api-gatewayaws-http-api

How to check http request method using API Gateway v2


My Architecture:

I'm trying to check the request method to handle actions, based on this answer they recomm

'use strict';

const AWS = require('aws-sdk');
const dynamo = new AWS.DynamoDB.DocumentClient();

exports.handler = async (event) => {

    switch (event.httpMethod) {
        case 'GET':
            break;
        default:
            throw new Error(`@@@@ Unsupported method "${event.httpMethod}"`);
    }
    return {
        statusCode: 200,
        body: JSON.stringify({message: 'Success'})
    };
};

I pasted that code just like that in my lambda and it doesn't work, I get this error in the logs:

"errorMessage": "@@@@ Unsupported method \"undefined\"",

That lambda is triggered by my HTTP API and the route has GET method.

If I return the event, I can see that the method is GET or POST, or whatever, look:

enter image description here

Anyone has any idea what's going on?


Solution

  • Input Object Schema for HTTP api (v2) is different to REST api (from your link).

    For a Http api, method can be obtained from event.requestContext.http.method

    so, it will look like this.

    exports.handler = async (event) => {
        console.log('event',event);
        switch (event.requestContext.http.method) {
            case 'GET':
                console.log('This is a GET Method');
                break;
            default:
                throw new Error(`@@@@ Unsupported method "${event.httpMethod}"`);
        }
        const response = {
            statusCode: 200,
            body: JSON.stringify('Hello from Lambda!'),
        };
        return response;
    };