Disable API Access
NotesDisabling Swagger Docs and APIs in the project may sound counterintuitive. However, since this project is a web application, removing public access to the APIs is okay, because they are not intended to be used as API endpoints. The views call the API functions directly, as Python functions, so the website keeps working without the API routes.
They’re still very useful during development, and for the automated tests. So rather than commenting code out, make it a setting. It’s off by default, so a production server is safe even if nobody remembers to change it, and you turn it on for development:
CONF_ENABLE_APIS: bool = False # NEWCONF_ENABLE_APIS=trueThe APIs in this guide have no authentication of their own. Anyone who can reach them could create or delete blog posts (and, after the next chapter, create users). Only ever enable them in development.
To disable the Swagger docs at /docs and /redoc, set openapi_url=None, which removes the OpenAPI schema they’re built from:
# Swagger UI and the OpenAPI schema are only published when the APIs are enabled
main_app = FastAPI(openapi_url="/openapi.json" if settings.CONF_ENABLE_APIS else None) # UPDATEDAnd only include the API routers when they’re enabled. Keep the health API either way, for monitoring purposes:
def configure_routing():
main_app.mount('/static', StaticFiles(directory='web/static'), name='static')
main_app.mount(settings.CONF_IMAGE_UPLOADS_CONTEXT_PATH.rstrip('/'),
StaticFiles(directory=settings.CONF_IMAGE_UPLOADS_FILE_PATH, check_dir=False),
name='uploads')
main_app.include_router(health_api.router, prefix=settings.CONF_API_V1_STR, tags=["health"])
if settings.CONF_ENABLE_APIS: # NEW
main_app.include_router(blog_apis.router, prefix=settings.CONF_API_V1_STR, tags=["blog_apis"]) # UPDATED
main_app.include_router(home_view.router, tags=["web_views"])
main_app.include_router(blog_views.router, tags=["web_views"])To try it, start the application with the setting turned off:
CONF_ENABLE_APIS=false fastapi dev main.py/docs and /api/v1/blog now return 404, while /api/v1/health and the website work as before.