I read the fastapi contrib code. Pagination available for mongodb only. Does fastapi has pagination module for postgres db also?
-
connections and queries to database is out of the scope of FastAPI right now. There is the https://fastapi-contrib.readthedocs.io/en/latest/fastapi_contrib.html#module-fastapi_contrib.pagination class that might be helpful. Currently there's no pre-built pagination solution included in FastAPI. – user368604 Feb 10 '20 at 14:55
-
https://stackoverflow.com/questions/63476011/fastapi-pagination-error-using-fastapi-contrib/64762432#64762432 – Moin Khan Nov 10 '20 at 03:32
3 Answers
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

- 543
- 4
- 10
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]

- 71
- 1
- 4
Currently, there is no built-in pagination system. You can look at fastapi-pagination module. Or you can do something like this:
def get_data(database: Session, page: int = 0, limit: int = 50):
# Note not the best option for large data sets.
try:
data = database.query(YourBaseModel).offset(page).limit(limit).all()
return data
except Exception as e:
logger.exception(e)
raise HTTPException(status_code=500, detail='There was an error while processing your request.')
And your API code:
@app.get('/data')
def example_data_api(database: Session = Depends(get_db), page: int = 0, limit: int = 50):
return get_data(database=database, page=page, limit=limit)

- 714
- 7
- 19