FastAPI DocShield: protect your API docs with one line
HTTP Basic Auth on the OpenAPI docs endpoints for FastAPI
Overview
FastAPI DocShield is a small library that locks down the auto-generated documentation endpoints on a FastAPI application. By default FastAPI exposes /docs, /redoc, and /openapi.json without authentication, which is fine in development but often unwanted in production. DocShield adds HTTP Basic Auth to those routes with a single import.
Why this exists
Most FastAPI apps in production want to keep the interactive docs around for internal teams but do not want every GoogleBot in the world crawling them. The obvious solutions are either to disable the docs in production (annoying when you need them) or to write a middleware manually (easy to get wrong). DocShield captures the right approach in a reusable package.
How it works
from fastapi import FastAPI
from fastapi_docshield import DocShield
app = FastAPI()
DocShield(app, username="admin", password="secret")
Behind the scenes it wraps the three doc endpoints with a dependency that checks the Authorization header for Basic credentials. If they match, the request proceeds. If they don't, a WWW-Authenticate header is returned so the browser prompts for credentials.
Security notes
Basic Auth is fine for this use case — you are protecting documentation, not user data. If the docs themselves contain sensitive information (internal endpoints, undocumented features), consider combining DocShield with a VPN or an IP allowlist so a credential leak cannot single-handedly expose the API surface.
Always use HTTPS in production. Basic Auth sends credentials in base64 encoding, which is trivially decoded if intercepted.
Tech stack
Pure FastAPI. No external dependencies beyond the framework itself.
Takeaway
Small libraries that do one thing well earn adoption. DocShield is ~50 lines of code and has saved me from writing the same middleware in three different projects.
