How to Access FastAPI SwaggerUI Docs Behind an NGINX proxy?

Viewed 3811

Hope you can help me, here is the issue I have:

Both of my frontend and backend servers runs on the same AWS EC2 instance. Because of this I have created a NGINX config like this:

server {
        server_name NAME;
        listen 80 default_server;
        location / {
                proxy_pass http://127.0.0.1:5000;
                proxy_set_header Host $http_host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_http_version 1.1;
        }
        location /api/ {
                proxy_pass http://127.0.0.1:8000;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $http_host;
                proxy_http_version 1.1;
        }
}

So any request to the "http://public_ip/api/" routed to the FastAPI backend server while every other request to another endpoint routed to the frontend SPA.

This works quite good mostly. However there is an issue if I try to access FastAPI "/api/docs" or "/api/redoc" routes. When I call the "/api/docs" endpoint for instance, there is a request to the "http://public_ip/openapi.json" address. And this isn't an endpoint starting with "/api" obviously. So NGINX blocks it and raises a bad request.

https://fastapi.tiangolo.com/advanced/behind-a-proxy/#about-proxies-with-a-stripped-path-prefix

I found this guide but it seems like this isn't related to my problem at all. At least I understand it that way.

Any help is appreciated. Thanks in advance.

1 Answers

Passing 'openapi_url' argument to the FastAPI() seems like good solution. Passed openapi_url= '/api/openapi.json' and it's fixed for both docs and redoc. Any other/better solution to handle all redirects that may occur is appreciated.

api = FastAPI(title="API_NAME",
              description="API_DESC",
              version="0.2.0",
              docs_url='/api/docs',
              redoc_url='/api/redoc',
              openapi_url='/api/openapi.json')
Related