question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

/openapi.json not found in Production when protecting API docs behind authentication

See original GitHub issue

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google “How to X in FastAPI” and didn’t find any information.
  • I already read and followed all the tutorial in the docs and didn’t find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

from fastapi import FastAPI, Depends, HTTPException, status
import secrets
from fastapi.security import HTTPBasic, HTTPBasicCredentials

from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.openapi.utils import get_openapi

security = HTTPBasic()

def get_current_username(credentials: HTTPBasicCredentials = Depends(security)):
    correct_username = secrets.compare_digest(credentials.username, "user")
    correct_password = secrets.compare_digest(credentials.password, "password")
    if not (correct_username and correct_password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect email or password",
            headers={"WWW-Authenticate": "Basic"},
        )
    return credentials.username

app = FastAPI(
    title = "Swagger", 
    root_path = "/api/assistant",
    version = "0.1.0",
    docs_url=None, redoc_url=None, openapi_url = None)

@app.get("/",)
def hello_world():
    return 'Hello, World!'

@app.get("/docs", include_in_schema=False)
async def get_documentation(username: str = Depends(get_current_username)):
    return get_swagger_ui_html(openapi_url="/openapi.json", title="Swagger")

@app.get("/openapi.json", include_in_schema=False)
async def openapi(username: str = Depends(get_current_username)):
    return get_openapi(title=app.title, version=app.version, routes=app.routes)

Description

Hi all, I am new to FastAPI. I migrated from Flask right away when I noticed how much simpler it is with FastAPI and how much better the support is. I am really glad that frameworks like this exist! 😃

The general stuff with setting everything up and using the APIs is working amazingly well. When deploying, I had to specify a root_path as described here https://fastapi.tiangolo.com/advanced/behind-a-proxy/ as I am deploying to a k8s cluster on Azure which is using nginx. That worked.

Now I want additionally to hide the documentation behind authentication, as described in #364 - the code works for me, but only on localhost. When deploying (of course still specifying the same root_path), after logging in on /docs I get the following message: image Which is the same as if I had not specified root_path. However, accessing /openapi.json via the browser manually works perfectly fine! I have no idea where the problem is coming from. I have been googling and trying out things for hours, but can’t find a solution here. I have a suspicion it has something to do with the routes=app.routes argment in get_openapi.

The example code is only partly helpful here, the problem really only occurs when the app is deployed. I checked the spelling, and I also tried passing root_path it via Dockerfile with no success.

Any help would be greatly appreciated!! Thank you so much.

Operating System

Windows

Operating System Details

No response

FastAPI Version

0.70.0

Python Version

3.9.2

Additional Context

No response

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:8 (2 by maintainers)

github_iconTop GitHub Comments

2reactions
DanielChromecommented, Sep 14, 2022

If you are using docker you can set the --root-path on docker-compose file. This solve my problem.

command: ["--root-path", "/api"],

2reactions
Jenjen1324commented, Dec 1, 2021

Funnily enough, I just came across this issue yesterday as well and solved it the same way as you did. But I did not have the issue you described (with the interactive api not working). I feel like this issue should stay open in any case though as the documentation should be updated to reflect this.

In order to solve this, I basically copied to code from fastapi itself: https://github.com/tiangolo/fastapi/blob/58ab733f19846b4875c5b79bfb1f4d1cb7f4823f/fastapi/applications.py#L166-L177

Which led to this result:

@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html(req: Request):
    root_path = req.scope.get("root_path", "").rstrip("/")
    openapi_url = root_path + app.openapi_url
    return get_swagger_ui_html(
        openapi_url=openapi_url,
        title="API",
    )

It doesn’t really differ from your solution… Nevertheless, make sure that the reverse proxy is stripping the path and the --root-url is passed into uvicorn.

My solution should also work for instances without --root-url in contrast to yours.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Conditional OpenAPI - FastAPI
Hiding your documentation user interfaces in production shouldn't be the way to protect your API. That doesn't add any extra security to your...
Read more >
Hello API Security + API Docs on Production? - SymfonyCasts
We've got API tokens, session-based authentication, CSRF attacks, dragon attacks and the challenge of securing our API Platform application down to the smallest ......
Read more >
How to configure Spring Security to allow Swagger URL to be ...
Main issue: Not able to access swagger URL at http://localhost:8080/api/v2/api-docs. It says Missing or invalid Authorization header. Screenshot ...
Read more >
Swagger API: Discovery of API data and security flaws
Swagger API is used in development and production environments. We researched Swagger APIs in Europe, the most common risks, and how to fix ......
Read more >
F.A.Q - Springdoc-openapi
The OpenAPI description of this group, will be available by default on: http://server:port/context-path/v3/api-docs/groupName.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found