Fastapi Tiangolo Com How To Conditional Openapi
Fastapi Tiangolo Com How To Conditional Openapi
Conditional OpenAPI
If you needed to, you could use settings and environment variables to con몭gure OpenAPI conditionally depending
on the environment, and even disable it entirely.
That doesn't add any extra security to your API, the path operations will still be available where they are.
Hiding the documentation just makes it more di몭cult to understand how to interact with your API, and could
make it more di몭cult for you to debug it in production. It could be considered simply a form of
Security through obscurity [↪].
If you want to secure your API, there are several better things you can do, for example:
Make sure you have well de몭ned Pydantic models for your request bodies and responses.
Implement and use well-known cryptographic tools, like Passlib and JWT tokens, etc.
Add more granular permission controls with OAuth2 scopes where needed.
...etc.
Nevertheless, you might have a very speci몭c use case where you really need to disable the API docs for some
environment (e.g. for production) or depending on con몭gurations from environment variables.
For example:
class Settings(BaseSettings):
openapi_url: str = "∕openapi.json"
settings = Settings()
app = FastAPI(openapi_url=settings.openapi_url)
app = FastAPI(openapi_url=settings.openapi_url)
@app.get("∕")
def root():
return {"message": "Hello World"}
Here we declare the setting openapi_url with the same default of "∕openapi.json".
Then you could disable OpenAPI (including the UI docs) by setting the environment variable OPENAPI_URL to the
empty string, like:
Then if you go to the URLs at ∕openapi.json, ∕docs, or ∕redoc you will just get a 404 Not Found error like:
{
"detail": "Not Found"
}