FastAPI.Path : TypeError: Path() missing 1 required positional argument: 'default'

Question:

From tutorials I’ve seen the below used. However, when I try to replicate (running Docker container locally) I observe the below error.

@app.get("/get-student/{student_id}") # path parameters and query parameters have no overlap
def get_student(student_id: int = Path(
        description="student ID", 
        gt=0 #minimum ID = 1,        
        )
    ):
    return students[student_id]

Error:

  File "/code/app/main.py", line 37, in <module>
    def get_student(student_id: int = Path(
TypeError: Path() missing 1 required positional argument: 'default'

When I review official documentation, default is not passed in as an argument. Nor do I see any data on how it should be used.

This leads me to two questions:

  1. Why is default required in my use case?
  2. Is using a Path best practice / what problem does it solve?

Edit: Documentation claims that adding * as the first arg will resolve. However, I have not observed this to be the case.

from fastapi import FastAPI, Path

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(*, item_id: int = Path(title="The ID of the item to get"), q: str):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

Additionally Docs also call for using Annotated, however, I’m still observing the same error:

@app.get("/get-student/{student_id}") # path parameters and query parameters have no overlap
def get_student(student_id = Annotated[int, Path(
        description="student ID", 
        gt=0 #minimum ID = 1,        
        )]):
    return students[student_id]
Asked By: jbuddy_13

||

Answers:

You’re referencing documentation for the latest version of FastAPI but up until 0.78.0 you needed to specify a value for default (usually ...) when specifying other optional arguments.

From the release notes:

✨ Add support for omitting … as default value when declaring required parameters with:

Path()

Up to now, declaring a required parameter while adding additional validation or metadata needed using … (Ellipsis).

Answered By: Woodford
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.