Python / Uvicorn Fundamentals Interview Questions
What is the --root-path setting in Uvicorn and when do you need it?
The --root-path setting tells Uvicorn (and consequently your ASGI application) that it is mounted at a specific URL path prefix. This is needed when your application is served at a sub-path behind a reverse proxy - for example, your app is at https://example.com/api/v1/ rather than https://example.com/.
# Without root-path: app thinks it lives at / # Nginx config: location /api/v1/ { proxy_pass http://127.0.0.1:8000; } uvicorn main:app # scope["root_path"] == "" # With root-path: app knows it is mounted at /api/v1 uvicorn main:app --root-path /api/v1 # scope["root_path"] == "/api/v1" # FastAPI uses root_path for generating correct OpenAPI docs URLs # Without it, /docs links will be wrong when behind a proxy from fastapi import FastAPI app = FastAPI(root_path="/api/v1") # set in the app OR in Uvicorn CLI # Programmatic: uvicorn.run("main:app", root_path="/api/v1")
Why it matters in FastAPI: FastAPI uses the ASGI root_path to generate the correct URLs in its OpenAPI (Swagger) documentation. Without setting it, the generated API docs will have incorrect base URLs when the app is served from a sub-path, causing all Try it out requests in Swagger UI to fail.
More Related questions...