fromfastapiimportFastAPIfromfastapi_paginationimportPage,add_pagination,paginateapp=FastAPI()add_pagination(app)# req: GET /users?page=2&size=10@app.get("/users")asyncdefget_users()->Page[int]:returnpaginate([*range(100)])
Steps:
Import Page, add_pagination, and paginate from fastapi_pagination.
Create a FastAPI application instance.
Add pagination support to the FastAPI application using add_pagination.
Define a route handler that returns a paginated response Page[int].
Use the paginate function to paginate the data and return the paginated response.
Warning
The paginate function is used to paginate the data that already exists in memory.
If you are working with a database or an ORM, you should use the appropriate methods provided by
the database or ORM to paginate the data.
The example above will be equal to the following vanilla FastAPI code:
fromfastapiimportFastAPI,Dependsfromfastapi_paginationimportPage,Params,paginate,set_pageapp=FastAPI()# req: GET /users?page=2&size=10@app.get("/users")asyncdefget_users(params:Params=Depends())->Page[int]:set_page(Page[int])returnpaginate([*range(100)],params)