Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda return only 200 respose code

I have created a sample lambda function for producing success & error responses. function is like below

exports.handler = (event, context, callback) => {
if(event.val1=="1")
{
 callback(null, 'success');
}else
{
 callback(true, 'fail');
}
};

When i have tested this function using API Gateway , I got different response body, But the response code is Same (always return 200 ok response code).

Is it possible to customize status code from lambda function(eg: need 500 for error responses & 200 for success responses)?

like image 301
Abdul Manaf Avatar asked Sep 21 '16 13:09

Abdul Manaf


Video Answer


2 Answers

You may want to look at API Gateway's new simplified Lambda proxy feature.

Using this you can define your status codes, return headers and body content directly from your Lambda.

Example from docs:

'use strict';
console.log('Loading hello world function');

exports.handler = function(event, context) {
    var name = "World";
    var responseCode = 200;
    console.log("request: " + JSON.stringify(event));
    if (event.queryStringParameters !== null && event.queryStringParameters !== undefined) {
        if (event.queryStringParameters.name !== undefined && event.queryStringParameters.name !== null && event.queryStringParameters.name !== "") {
            console.log("Received name: " + event.queryStringParameters.name);
            name = event.queryStringParameters.name;
        }

        if (event.queryStringParameters.httpStatus !== undefined && event.queryStringParameters.httpStatus !== null && event.queryStringParameters.httpStatus !== "") {
            console.log("Received http status: " + event.queryStringParameters.httpStatus);
            responseCode = event.queryStringParameters.httpStatus;
        }
    }

    var responseBody = {
        message: "Hello " + name + "!",
        input: event
    };
    var response = {
        statusCode: responseCode,
        headers: {
            "x-custom-header" : "my custom header value"
        },
        body: JSON.stringify(responseBody)
    };
    console.log("response: " + JSON.stringify(response))
    context.succeed(response);
};
like image 114
Bob Kinney Avatar answered Sep 17 '22 13:09

Bob Kinney


In order to send a custom error code from AWS API GW you should use response mapping template in integration response. You basically define a regular expression for each status code you'd like to return from API GW.

Steps:

  • Define Method Response for each status code AWS Documentation
  • Define Integration Response RegEx for each status mapping to the Correct Method Response AWS Documentation

Using this configuration the HTTP return code returned by API GW to the client is the one matching the regular expression in "selectionPattern".

Finally I strongly suggest to use an API GW framework to handle these configuration, Serverless is a very good framework.

Using Servereless you can define a template as follows (serverless 0.5 snippet):

myResponseTemplate:
application/json;charset=UTF-8: |
#set ($errorMessageObj = $util.parseJson($input.path('$.errorMessage'))) {
    "status" : $errorMessageObj.status,
    "error":{
        "error_message":"$errorMessageObj.error.message",
        "details":"$errorMessageObj.error.custom_message"
    }
}
responsesValues:
'202':
  selectionPattern: '.*"status": 202.*'
  statusCode: '202'
  responseParameters: {}
  responseModels: {}
  responseTemplates: '$${myResponseTemplate}'
'400':
  selectionPattern: '.*"status": 400.*'
  statusCode: '400'
  responseParameters: {}
  responseModels: {}
  responseTemplates: '$${myResponseTemplate}'

Then simply return a json object from your lambda, as in the following python snippet (you can use similar approach in nodejs):

 def handler(event, context):
     # Your function code ...
     response = { 
         'status':400, 
         'error':{
             'error_message' : 'your message',
             'details' : 'your details'
          }
     }
    return response

I hope this helps.

G.

like image 26
Girolamo Piccinni Avatar answered Sep 17 '22 13:09

Girolamo Piccinni