The items transformer allows to transform the items before they are returned in the response.
This can be useful for formatting the data or adding additional information to the items.
It's a class that accepts a chunk of items and returns a new chunk of items that will be used in the response.
fromfastapiimportFastAPIfromfastapi_paginationimportPage,add_pagination,paginateapp=FastAPI()add_pagination(app)# req: GET /ints?page=2&size=5@app.get("/ints")asyncdefroute()->Page[int]:returnpaginate(range(100),transformer=lambdaitems:[item*2foriteminitems],# double the items)
Items transformer can be also set globally:
fromfastapiimportFastAPIfromfastapi_paginationimportPage,add_pagination,paginatefromfastapi_pagination.apiimportset_items_transformerapp=FastAPI()add_pagination(app)set_items_transformer(lambdaitems:[item*2foriteminitems])# req: GET /ints?page=2&size=5@app.get("/ints")asyncdefroute()->Page[int]:returnpaginate(range(100))# req: GET /another-ints?page=2&size=5@app.get("/another-ints")asyncdefanother_route()->Page[int]:returnpaginate(range(100))
Or per route:
fromfastapiimportFastAPIfromfastapi_paginationimportPage,add_pagination,paginatefromfastapi_pagination.apiimportset_items_transformerapp=FastAPI()add_pagination(app)# req: GET /ints?page=2&size=5@app.get("/ints")asyncdefroute()->Page[int]:set_items_transformer(lambdaitems:[item*2foriteminitems])returnpaginate(range(100))# req: GET /ints-no-transformer?page=2&size=5@app.get("/ints-no-transformer")asyncdefanother_route()->Page[int]:returnpaginate(range(100))
If paginate function is async, then the transformer can be async too:
fromfastapiimportFastAPIfromfastapi_paginationimportPage,add_paginationfromfastapi_pagination.async_paginatorimportpaginateapp=FastAPI()add_pagination(app)asyncdeftransformer(items:list[int])->list[int]:return[item*2foriteminitems]# req: GET /ints?page=2&size=5@app.get("/ints")asyncdefroute()->Page[int]:returnawaitpaginate(range(100),transformer=transformer)