Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python FastAPI base path control

Tags:

python

fastapi

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" }
like image 837
JimmyNJ Avatar asked Apr 19 '26 08:04

JimmyNJ


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.

Note: a path prefix must start with / (Thanks to Harshal Perkh for this)

like image 138
Hans Bambel Avatar answered Apr 20 '26 22:04

Hans Bambel


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

like image 26
Luca Capra Avatar answered Apr 20 '26 22:04

Luca Capra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!