Passing Authorization Headers in Swagger Documentation for FastAPI
When building APIs with FastAPI, it's crucial to have well-structured documentation for developers. Swagger, integrated with FastAPI, provides a fantastic solution for this. However, when working with APIs that require authentication, passing authorization headers to the Swagger UI becomes a necessity. This article will guide you on how to effectively achieve this in your Python FastAPI application.
The Problem: Missing Authorization in Swagger
Imagine a scenario where you've developed a FastAPI endpoint that requires authentication using JWT tokens. You've successfully implemented the authentication logic in your code. However, when accessing your API documentation through Swagger UI, you're unable to test the endpoint because the authorization header is missing. This can hinder developers from properly interacting with your API during development.
Implementing Authorization in Swagger
Here's a typical FastAPI route that requires authorization:
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@app.get("/protected")
async def protected_endpoint(token: str = Depends(oauth2_scheme)):
# Your authentication logic here
# ...
return {"message": "Protected endpoint accessed!"}
This route uses a Depends
dependency to extract the JWT token from the Authorization
header. However, Swagger UI currently doesn't provide a way to automatically include the token in requests.
Solution: Customizing Swagger UI
To overcome this limitation, we'll utilize a custom security scheme in Swagger. The SecurityScheme
object in OpenAPI specifications allows us to define custom authorization methods. Here's the updated FastAPI code:
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.openapi.utils import get_openapi
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@app.get("/protected")
async def protected_endpoint(token: str = Depends(oauth2_scheme)):
# Your authentication logic here
# ...
return {"message": "Protected endpoint accessed!"}
@app.get("/docs")
async def custom_swagger_ui_html():
return get_swagger_ui_html(
openapi_url=app.openapi_url,
title=app.title + " - Swagger UI",
oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,
swagger_js_url="/static/swagger-ui/swagger-ui-bundle.js",
swagger_css_url="/static/swagger-ui/swagger-ui.css",
)
@app.get("/openapi.json")
async def openapi_json():
return get_openapi(
title="My API",
version="1.0.0",
routes=app.routes,
openapi_version="3.0.2",
security_schemes={
"bearerAuth": {
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT",
},
},
)
app.openapi_url = "/openapi.json"
app.swagger_ui_oauth2_redirect_url = app.url_path_for("oauth2_redirect")
@app.get("/oauth2_redirect")
async def oauth2_redirect():
return {"message": "Authorization completed"}
Explanation:
- Custom Security Scheme: We define a
security_scheme
within theopenapi.json
endpoint withtype
ashttp
andscheme
asbearer
. - BearerFormat: We set
bearerFormat
toJWT
, signifying the authorization method uses JWT tokens. - Swagger UI Integration: The
get_swagger_ui_html
function ensures Swagger UI uses our custom OpenAPI specification with the defined security scheme.
Now, when you navigate to the /docs
endpoint, the Swagger UI will display a Authorization
section where you can enter your JWT token. This token will be automatically included in the header of subsequent requests to the /protected
endpoint.
Best Practices
- Token Management: Always store and manage JWT tokens securely. Do not hardcode them directly into the UI.
- Security: Use HTTPS to protect sensitive information transmitted between the client and the server.
- Documentation: Clearly document the authentication process and provide instructions on obtaining and using JWT tokens in your API documentation.
Conclusion
By utilizing custom security schemes in Swagger, you can seamlessly integrate authentication into your FastAPI application and provide a more complete development experience. This ensures that developers can easily test your API endpoints while adhering to security best practices.