Add query params into the Page
jochman opened this issue · 7 comments
jochman commented
I want to add the query parameters into the page data. How can I do that?
jochman commented
Hi! thanks for answering.
from fastapi import FastAPI
from pydantic import BaseModel, Field
# import all you need from fastapi-pagination
from fastapi_pagination import Page, add_pagination, paginate
app = FastAPI() # create FastAPI app
class UserOut(BaseModel): # define your model
name: str = Field(..., example="Steve")
surname: str = Field(..., example="Rogers")
users = [ # create some data
# ...
]
@app.get('/users')
async def get_users(name: str) -> Page[UserOut]: # use Page[UserOut] as return type annotation
return paginate(users, filter(x: x.name == name)) # use paginate function to paginate your data
add_pagination(app) # important! add pagination to your app
I want to have at the output page something like :
{
"items": [],
"query": {
"name": "my name"
},
...
}
of course, not problem to define that manually.
uriyyo commented
Easiest option will be to allow extra fields:
from fastapi import FastAPI, Query
from pydantic import BaseModel, Field
from fastapi_pagination import Page, add_pagination, paginate
from fastapi_pagination.customization import CustomizedPage, UseModelConfig
app = FastAPI()
class UserOut(BaseModel):
name: str = Field(..., example="Steve")
surname: str = Field(..., example="Rogers")
users = [ # create some data
UserOut(
name="Tony",
surname="Stark",
),
]
Page = CustomizedPage[
Page,
UseModelConfig(extra="allow"),
]
@app.get("/users")
async def get_users(name: str = Query(None)) -> Page[UserOut]:
return paginate(
users,
additional_data={"query": {"name": name}},
)
add_pagination(app)
jochman commented
How from fastapi_pagination.links import Page
reacts with query params for link building?
uriyyo commented
It works as expected:
from fastapi import FastAPI, Query
from pydantic import BaseModel, Field
from fastapi_pagination import add_pagination, paginate
from fastapi_pagination.links import Page
from fastapi_pagination.customization import CustomizedPage, UseModelConfig
app = FastAPI()
class UserOut(BaseModel):
name: str = Field(..., example="Steve")
surname: str = Field(..., example="Rogers")
users = [ # create some data
UserOut(
name="Tony",
surname="Stark",
),
]
Page = CustomizedPage[
Page,
UseModelConfig(extra="allow"),
]
@app.get("/users")
async def get_users(name: str = Query(None)) -> Page[UserOut]:
return paginate(
users,
additional_data={"query": {"name": name}},
)
add_pagination(app)
GET http://localhost:8000/users?name=Tony
{
"items": [
{
"name": "Tony",
"surname": "Stark"
}
],
"total": 1,
"page": 1,
"size": 50,
"pages": 1,
"links": {
"first": "/users?name=Tony&page=1",
"last": "/users?name=Tony&page=1",
"self": "/users?name=Tony",
"next": null,
"prev": null
},
"query": {
"name": "Tony"
}
}
jochman commented
I just got back to that. Will keep you updated :)
but the solution seems right. thanks