Fastapi: [BUG] auto-rewrite doesn't take openapi_prefix into account

Created on 20 May 2020  路  6Comments  路  Source: tiangolo/fastapi

Describe the bug

The problem is basically the one described here:
https://github.com/tiangolo/fastapi/issues/51#issuecomment-522035784
My fastapi app is behind a reverse proxy that forwards all requests for /api/v1/* and rewrites them to /*.
The application itself doesn't know that but the FastAPI object which has openapi_prefix="/api/v1".

If I have an endpoint

@app.get("/hello")
def foo():
    return "hello"

and I query /api/v1/hello, it works fine. If I add an extra slash at the end, a redirect occurs but tries to send the user to /hello instead of /api/v1/hello.
I'm not sure if it's a bug or if I don't use the app correctly. Maybe it would be simpler for me to make the fastapi app aware of the /api/v1 prefix and remove the rewrite rule? What do you think?

To Reproduce

Behind a reverse proxy forwarding the requests for /api/v1/* and rewriting those to /*

  1. Create a file with:
from fastapi import FastAPI

app = FastAPI(openapi_prefix="/api/v1")


@app.get("/hello")
def read_root():
    return {"Hello": "World"}
  1. Open the browser and call the endpoint /api/v1/hello/.
  2. It returns a 404 because there is a redirect to /hello.
  3. But I expected the redirect to be to /api/v1/hello.

Expected behavior

The redirection shouldn't remove the openapi_prefix.

Environment

  • OS: Linux / Windows
  • FastAPI Version 0.52.0 from pip
  • python 3.7.4.
answered bug

Most helpful comment

@tiangolo Hello. I just tested my app by replacing the openapi_prefix parameter by root_path on the FastAPI object: it works like a charm. I'll close this issue.
Thanks a lot!

All 6 comments

@tiangolo any way i could possibly work on this? looks very interesting

Thanks for the help here @phy25 ! :coffee: :cake:

@Gaasmann there's is new, improved support for root_path, the part of the ASGI spec that deals with reverse proxies, there's a new example in the docs here: https://fastapi.tiangolo.com/advanced/behind-a-proxy/

Please check with a recent version, following that guide, it might be what you need :rocket:


@rkbeatss I think we can try something related to this, but maybe more related to https://github.com/tiangolo/fastapi/issues/1294. There's recently support for servers (from OpenAPI). Maybe we could, whenever there's a root_path, with some value, add it to the servers in OpenAPI instead of prefixing all the paths in get_openapi(). I'm still not sure how/if that would work and what else needs to be changed, but it might be worth trying :smile: :nerd_face:

@tiangolo will start investigating this today
bitmoji

@tiangolo Hello. I just tested my app by replacing the openapi_prefix parameter by root_path on the FastAPI object: it works like a charm. I'll close this issue.
Thanks a lot!

Thanks for reporting back and closing the issue @Gaasmann :tada: :+1:

Was this page helpful?
0 / 5 - 0 ratings