Dominux
Dominux

Reputation: 239

FastAPI: passing path params via included routers

In symplified case we've got a projects and files. Files belong to projects. Every of them has their own router to perfom CRUD actions via API.

So, in code it should look like this:

from fastapi import FastAPI, APIRouter

app = FastAPI()

projects_router = APIRouter()
files_router = APIRouter()

app.include_router(projects_router, prefix="/projects")
projects_router.include_router(files_router, prefix="/{project_id}/files")

@files_router.get("/")
def list_files(project_id: int):
    # Some code, that list all project's files by project_id

But the list_files function can't get project_id. How can it?

Upvotes: 1

Views: 2143

Answers (1)

H. Sinan Alioglu
H. Sinan Alioglu

Reputation: 11

You need to add project_id as a path parameter. By default it's a query parameter. Three dots ... in Path parameter make it required:

from fastapi import Path
@files_router.get("/")
def list_files(project_id: int = Path(..., gt=0)):
    # Some code, that list all project's files by project_id

Upvotes: 0

Related Questions