[QUESTION] Protect API docs behind authentication?
See original GitHub issueBasic Question
Does FastAPI provide a method for implementing authentication middleware or similar on the docs themselves (e.g. to protect access to /docs
and /redoc
)?
Additional context
My company is currently relying on a needlessly-complex Django backend, whose main purpose is serving an API via the Django REST framework. However, it feels like half the bugs the frontend app folks are running into are caused by a disconnect between what the Django app is doing and the API documentation wiki (which is maintained by hand; it’s a monster).
FastAPI thus looks like a perfect alternative. However, it’s a requirement for us that the API documentation only be accessible to specific authenticated users. It looks like I could easily disable the docs when run in a production environment (as opposed to a local testing environment), but if it’s possible to serve the docs on production but explicitly protect them that would be ideal (the API in part facilitates interaction between frontend apps and IOT devices, so the interactive portions of the docs would be a lot easier to use and maintain on specific hosted servers; setting up working local environments is complicated).
In my ideal world, I’d love to also auto-populate the initial authentication credentials for the interactive queries with the current user’s authentication token (to allow no-configuration usage of them immediately upon access). I wasn’t able to find anything in the FastAPI docs about meddling with the way the documentation is handled, but if I missed it I’d love a link!
Issue Analytics
- State:
- Created 4 years ago
- Comments:13 (3 by maintainers)
Top GitHub Comments
Hi there, I just find an easy solution to this question.
You can simply disable default /docs and create docs behind authentication
Example code:
Pro tips
Using ReDoc If you prefer ReDoc, you can use it just replacing
get_swagger_ui_html
byget_redoc_html
… Or you can use both…Hiding those endpoints You are adding 2 new endpoints to your API and, almost for sure, it won’t be very useful to show them in your documentation. You can hide them by including the parameter
include_in_schema=False
to the@app.get( ... )
decorators.A small improvement for code mantainance It might be a bit better to define the title and version in the inside of
app = FastAPI( ... )
and use:instead of
This way, every-time you change the version (or if you need to change the title in the future), you can do it where you would normally do it and you won’t have to remember where is that defined. Save time for the future you.
Final code After does changes, this would be the final code:
Final words: Just remember this is an example and you still need to connect this small authentication code to your real login system or, at least, use environment variables. If you are protecting your API documentation, just don’t hard code your credentials…