redirecting from aws api gateway using response 302
I am trying to make the redirect work in AWS API gateway. I configured the method response to include Location in the header and on the Integration Response, I set the parameter as : Location = integration.response.body.location. however, when I test the API, instead of redirecting me to the location, it just shows me the text for the location on the API page. Has anyone encountered this before?
The string shown is actually the correct location but the API does not redirect me to that URL.
It's possible to redirect to a hardcoded URL using API Gateway without using AWS Lambda. Here's the exported OpenAPI 3.0 definition for how this is accomplished:
openapi: "3.0.0"
info:
title: 'TheApiName'
version: ''
paths:
"/":
get:
responses:
"302":
description: "302 response"
headers:
Location:
schema:
type: "string"
content: {}
x-amazon-apigateway-integration:
responses:
default:
statusCode: "302"
responseParameters:
method.response.header.Location: "'https://github.com/lukedemi/adventbot'"
requestTemplates:
application/json: "{\"statusCode\": 200}"
passthroughBehavior: "when_no_match"
type: "mock"
Note that when you import this API template you still need to "Deploy" it, and you need to create a "Stage" when doing so and then associate the API:Stage with a Custom Domain (which requires an ACM cert when first creating the custom domain in API Gateway) and then you can ONLY deploy this single API to the domain since you need to use an empty basepath (which resolves to /
) and that mapping doesn't allow any other /anything
routes due to the way API Gateway works.
There is a simpler way for Lambda redirects with API Gateway:
module.exports.handler = (event, context, callback) => Promise.resolve(event)
// .then(doStuffWithTheEventObject)
.then(() => callback(null, {
statusCode: 302,
headers: {
Location: 'https://gohere.com',
},
})) // Success!
.catch(callback); // Fail function with error
This example is from https://blog.rowanudell.com/redirects-in-serverless/