One of my endpoints is supposed to be pageable. It's essentially just a wrapper around an external API, thus there's some workarounds unfortunately.
However, I'd like to know how I can set the params: Params via query parameters.
I expected there to be arguments page and size to be available as in /search?page=2&size=10 declaring them.
Since I wasn't able to find a single example I thought I might ask.
@search_router.get("/search")
def search(query: str, params: Params = Params(size=20), response_model=Page[dict]):
result = ris_client.service.SearchDocuments({
"DokumenteProSeite": PAGE_SIZE[params.size],
"Seitennummer": params.page
})
results = result["results"]
hits = results["hits"]
content = results["references"]
return paginate(
content,
params,
length_function=lambda _: int(hits["value"])
)
I know I could expose these parameters myself like so:
@search_router.get("/search")
def search(query: str, size: int = 20, page: int = 0, response_model=Page[dict]):
params = Params(size=size, page=page)
# ...
return paginate(
content,
params,
length_function=lambda _: int(hits["value"])
)
but why is it then that I see the Params class in the function signature in almost every tutorial?
This Params from fastapi-pagination is just a small helper class, that does some prevalidation for you:
class Params(BaseModel, AbstractParams):
page: int = Query(1, ge=1, description="Page number")
size: int = Query(50, ge=1, le=100, description="Page size")
def to_raw_params(self) -> RawParams:
return RawParams(
limit=self.size,
offset=self.size * (self.page - 1),
)
You can use it instead of explicitly passing those parameters to your endpoint.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With