When I use FastAPI , how can I sepcify a base path for the web-service?
To put it another way - are there arguments to the FastAPI object that can set the end-point and any others I define, to a different root path?
For example , if I had the code with the spurious argument root below, it would attach my /my_path end-point to /my_server_path/my_path ?
from fastapi import FastAPI, Request
app = FastAPI(debug = True, root = 'my_server_path')
@app.get("/my_path")
def service( request : Request ):
return { "message" : "my_path" }
You can use an APIRouter and add it to the app after adding the paths:
from fastapi import APIRouter, FastAPI
app = FastAPI()
prefix_router = APIRouter(prefix="/my_server_path")
# Add the paths to the router instead
@prefix_router.get("/my_path")
def service( request : Request ):
return { "message" : "my_path" }
# Now add the router to the app
app.include_router(prefix_router)
When adding the router first and then adding paths it does now work. It seems that the paths are not detected dynamically.
Note: a path prefix must start with / (Thanks to Harshal Perkh for this)
From documentation, if you are using a reverse proxy then you could achieve the same with
uvicorn main:app --root-path /api/v1
reference https://fastapi.tiangolo.com/advanced/behind-a-proxy/?h=prefix#testing-locally-with-traefik
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With