Conditional OpenAPI
The current page still doesn’t have a translation for this language.
But you can help translating it: Contributing.
If you needed to, you could use settings and environment variables to configure OpenAPI conditionally depending on the environment, and even disable it entirely.
Hiding your documentation user interfaces in production shouldn’t be the way to protect your API.
If there’s a security flaw in your code, it will still exist.
Hiding the documentation just makes it more difficult to understand how to interact with your API, and could make it more difficult 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 defined Pydantic models for your request bodies and responses.
- Never store plaintext passwords, only password hashes.
- Implement and use well-known cryptographic tools, like Passlib and JWT tokens, etc.
- Add more granular permission controls with OAuth2 scopes where needed.
Nevertheless, you might have a very specific use case where you really need to disable the API docs for some environment (e.g. for production) or depending on configurations from environment variables.
Conditional OpenAPI from settings and env vars
For example:
Here we declare the setting with the same default of "/openapi.json"
.
And then we use it when creating the FastAPI
app.
Then you could disable OpenAPI (including the UI docs) by setting the environment variable to the empty string, like:
Then if you go to the URLs at /openapi.json
, /docs
, or you will just get a 404 Not Found
error like:
{
}