Python FastAPI base path control

Viewed 4112

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" }
2 Answers

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.

I think you need the prefix option.

Add this after creating app:

app.include_router(prefix="/my_server_path")

Related