First Steps
Here is an example:
from fastapi import FastAPI
from fastapi_pagination import Page, add_pagination, paginate
app = FastAPI()
add_pagination(app)
# req: GET /users?page=2&size=10
@app.get("/users")
async def get_users() -> Page[int]:
return paginate([*range(100)])
Steps:
- Import
Page
,add_pagination
, andpaginate
fromfastapi_pagination
. - Create a
FastAPI
application instance. - Add pagination support to the
FastAPI
application usingadd_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:
from fastapi import FastAPI, Depends
from fastapi_pagination import Page, Params, paginate, set_page
app = FastAPI()
# req: GET /users?page=2&size=10
@app.get("/users")
async def get_users(params: Params = Depends()) -> Page[int]:
set_page(Page[int])
return paginate([*range(100)], params)