By default, if you are using the add_pagination function, then the only thing you need to do is to use the
response_model or set the return type annotation to be a subclass of AbstractPage.
fromfastapiimportFastAPIfromfastapi_paginationimportPage,add_pagination,paginateapp=FastAPI()add_pagination(app)# req: GET /return-type-ann?page=2&size=5@app.get("/return-type-ann")asyncdefroute()->Page[int]:returnpaginate(range(100))# req: GET /return-model?page=2&size=5@app.get("/return-model",response_model=Page[int])asyncdefroute():returnpaginate(range(100))
If you want to return a non-Page response model, you can use the set_page function to set the response model, but
then you will need to explicitly specify the params value in the route handler.
fromtypingimportAnnotatedfromfastapiimportFastAPI,Dependsfromfastapi_paginationimportParams,Page,paginate,set_pageapp=FastAPI()# req: GET /non-page?page=2&size=5@app.get("/non-page")asyncdefroute(params:Annotated[Params,Depends()])->list[int]:set_page(Page[int])page=paginate(range(100),params=params)returnpage.items
Multiple Page response models for a single route handler¶
If you want to return multiple Page response models for a single route handler, you can use the response_model parameter
in the route declaration.
fromtypingimportAnyfromfastapiimportFastAPIfromfastapi_paginationimportPage,LimitOffsetPage,add_pagination,paginateapp=FastAPI()add_pagination(app)# req: GET /page?page=2&size=5@app.get("/page",response_model=Page[int])# req: GET /limit-offset?limit=5&offset=5@app.get("/limit-offset",response_model=LimitOffsetPage[int])asyncdefroute()->Any:returnpaginate(range(100))