How to return a 302 with Location header using API Gateway and Lambda
How can you map your Lambda success response to 302 with a Location header pointing to a new resource? Please follow the below steps to achieve it.
Here we have an example of a 302 response with the Location header set to the redirect location.
> HTTP/1.1 302 Found
> Content-Type: application/json
> Content-Length: 38
> Connection: keep-alive
> Location: https://www.example.com
Lambda Setup
Firstly we set up Lambda to return the value you want in the Location header
exports.handler = function(event, context) {
context.succeed({location: 'https://example.com'});
};
The property name location has should be matched with the value you will set later your API Gateway Integration Response.
API Gateway Method Response
When setting up the API Gateway Method Response, start by declaring the status code in the Method Response section. 200 will already.
Delete 302 response.
Add your 302 here instead and add the Location response header.
You declare what you're going to use but you don't actually link them up to your Lambda here. Integration Response is the area where you do that so that's where you head next.
API Gateway Integration Response
In Integration Response you'll see it set up for the 200 with the Regex set to default. Delete this mapping by clicking the X icon on the right side.
Now add a new integration response.
You'll be prompted to choose a status code from a list of codes that were declared back in Method Response.
Pick your 302. You also want to set up a Header Mapping for Location.
Make the mapping value integration.response.body.location against Location.
The last part of that string "location" has to match the value you are returning in your Lambda function.
Make sure you click the green check near the header mapping and the Save near the response regex.
You will see when we hit the API Gateway URL on the browser. We got a response from Lamda through API gateway as a 302 status code.
That's it.!!! We have seen how the return 302 with Location header using API Gateway and Lambda.
0 Comments
Post a Comment