I read the fastapi contrib code. Pagination available for mongodb only. Does fastapi has pagination module for postgres db also?
You can use fastapi-pagination
module, it currently has integration with sqlalchemy
and gino
.
The usage will look like:
from fastapi_pagination import Page, PaginationParams
from fastapi_pagination.ext.sqlalchemy import paginate
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String, nullable=False)
email = Column(String, nullable=False)
class UserModel(BaseModel):
id: int
name: str
email: str
class Config:
orm_mode = True
app = FastAPI()
@app.get('/users', response_model=Page[UserModel])
def get_users(db: Session = Depends(get_db), params: PaginationParams = Depends()):
return paginate(db.query(User), params)
Please notice, the purpose of this code is to show fastapi-pagination
API.
You can find a fully working example here: https://github.com/uriyyo/fastapi-pagination/blob/main/examples/pagination_sqlalchemy.py
There is not anything automatic built in to the library, but you can set it up via query parameters and pass it to your ORM, like the query object's offset() and limit() methods in SQL Alchemy.
This example from FastAPI's Query Parameter Documentation has them using it on a static dataset:
from fastapi import FastAPI
app = FastAPI()
fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
return fake_items_db[skip : skip + limit]
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