uriyyo / fastapi-pagination

FastAPI pagination 📖
https://uriyyo-fastapi-pagination.netlify.app/
MIT License
1.1k stars 126 forks source link

return custom headers #1125

Closed jochman closed 2 months ago

jochman commented 2 months ago

hi again!

I couldn't find a way to return headers with the paginate - I have headers that I would need to return with data from the page it pulls. Is there a way doing that?

uriyyo commented 2 months ago

Hi @jochman,

Sorry for long response.

You can access response using response function from fastapi_paganation.api package.

Here is an example:

from typing import Any, Optional, Sequence

from fastapi import FastAPI
from fastapi_pagination import Page, add_pagination, paginate, response
from fastapi_pagination.bases import AbstractParams

class MyPage[T](Page[T]):
    @classmethod
    def create(
        cls,
        items: Sequence[T],
        params: AbstractParams,
        *,
        total: Optional[int] = None,
        **kwargs: Any,
    ) -> Page[T]:
        page = super().create(items, params, total=total, **kwargs)

        response().headers["X-Total-Count"] = str(page.total)

        return page

app = FastAPI()
add_pagination(app)

@app.get("/items")
def route() -> MyPage[int]:
    return paginate([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app)
jochman commented 2 months ago

Wdyt about creating a plugin system like pydantic with Annotated and AfterValidator that get a function with kwargs of page, response?

uriyyo commented 2 months ago

Makes sense to me, I already started working on smth like this.

You can check it here - https://uriyyo-fastapi-pagination.netlify.app/tutorials_advanced/customization/

uriyyo commented 2 months ago

@jochman Can I close this issue?