Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FastAPI redirects to wrong host with Mangum #307

Open
richardcornelissen opened this issue Oct 13, 2023 · 2 comments
Open

FastAPI redirects to wrong host with Mangum #307

richardcornelissen opened this issue Oct 13, 2023 · 2 comments

Comments

@richardcornelissen
Copy link

richardcornelissen commented Oct 13, 2023

FastAPI responds with an HTTP 307 Temporary Redirect due to a missing or additional trailing slash (depending on the route). When this happens, it uses the Host header.

When using CloudFront instead of API Gateway's custom domains, the Host header is changed to [apiId].execute-api.[region].amazonaws.com and the original host is stored in an additional header x-original-host.

Combined, this causes requests to be redirected to an execute-api url instead of the intended host.

Related issues on FastAPI:

Workaround

As a temporary workaround, consider adding a wrapper around Mangum's handler

mangumHandler = Mangum(app, lifespan="off")

def handler(event: LambdaEvent, context: LambdaContext):
    if event["multiValueHeaders"]["x-original-host"]:
      event["multiValueHeaders"]["Host"] = event["multiValueHeaders"]["x-original-host"]
    response = mangumHandler(event, context)
    return response
@lukaszsamson
Copy link

Notice that the workaround does not work with lambda function URLs. In my case what fixed it was making sure my api endpoints does not have trailing /.

this results in a 307 redirect loop

@app.get("/test/")
def test_endpoint():

this works

@app.get("/test")
def test_endpoint():

@beck3905
Copy link

I ran into a similar issue, but also sort of opposite.

I am using API Gateway with custom domain names and Lambda Proxy integration. When I run Mangum I provide the api_gateway_base_path parameter and Mangum strips that from my path. However, that means that when I have a handler for a top level resource (i.e. "/") I can sometimes end up with an empty path if the user doesn't provide the trailing slash.

I ended up using the mangum.handlers.utils.strip_api_gateway_path method to check if I will end up with an empty path and then I append the trailing slash to the event path. If I don't append the trailing slash, then FastAPI tries to automatically redirect to the URL with the trailing slash, but API Gateway won't handle that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants