Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FastAPI RuntimeError: Use params or add_pagination

Tags:

fastapi

I'm writing my second project on FastAPI. And I got this error. For example I have this code in my routers.users.py:

@router.get('/', response_model=Page[Users])
async def get_all_users(db: Session = Depends(get_db)):
    return paginate(db.query(models.User).order_by(models.User.id))

And it works. It has fields limit and page in swagger documentation. I tried to write the same for routers.recipes.py, but in this case I have no fields for pagination(limit, page) in swagger. Ok, I googled and found out that adding dependencies could help me. And now I see pagination parameters in swagger, but error is still the same.

routers.recipes:

@router.get('/', response_model=Page[PostRecipes], dependencies=[Depends(Params)])
async def get_all_recipes(db: Session = Depends(get_db)):
    return paginate(db.query(models.Recipe).order_by(models.Recipe.id))

pagination:

class Params(BaseModel, AbstractParams):
    page: int = Query(1, ge=1, description="Page number")
    limit: int = Query(50, ge=1, le=100, description="Page size")

    def to_raw_params(self) -> RawParams:
        return RawParams(
            limit=self.limit,
            offset=self.limit * (self.page - 1),
        )


class Page(BasePage[T], Generic[T]):
    page: conint(ge=1)  # type: ignore
    limit: conint(ge=1)  # type: ignore

    __params_type__ = Params

    @classmethod
    def create(
        cls,
        items: Sequence[T],
        total: int,
        params: AbstractParams,
    ) -> Page[T]:
        if not isinstance(params, Params):
            raise ValueError("Page should be used with Params")

        return cls(
            total=total,
            items=items,
            page=params.page,
            limit=params.limit,
        )


__all__ = [
    "Params",
    "Page",
]

So, does anyone have ideas about it?

like image 992
Konstantinos Avatar asked Aug 25 '26 20:08

Konstantinos


2 Answers

In my case this was only happening while running tests against paginated endpoints. The solution was to call add_pagination(app) after including the related routers in the app, and not before:

app = FastAPI()

app.include_router(some_router)

# This should be done after all calls to app.include_router()
add_pagination(app)

I think the underlying reason for this is that when using FastAPI's TestClient, startup events are not emitted by default, but fastapi_pagination uses them under the hood: https://fastapi.tiangolo.com/advanced/testing-events/

like image 187
Alexander Avatar answered Sep 03 '26 23:09

Alexander


I ran into this problem earlier. In my case, I forgot to update the response_model for the paginated endpoint.

@router.get(
    "",
    summary="",
    description="",
    response_model=List[DealerModel], # type error here
)
async def filter_companies(db: Session = Depends(get_db)):
    return paginate(crud.filter_companies(db))

Should be response_model=Page[DealerModel],

like image 40
Samuel RIGAUD Avatar answered Sep 03 '26 22:09

Samuel RIGAUD



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!