Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does fastapi contrib has paginator for postgresql?

I read the fastapi contrib code. Pagination available for mongodb only. Does fastapi has pagination module for postgres db also?

like image 310
user12747053 Avatar asked Feb 10 '20 14:02

user12747053


2 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

like image 50
Yurii Karabas Avatar answered Sep 17 '22 22:09

Yurii Karabas


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]
like image 35
Lucas Tieman Avatar answered Sep 20 '22 22:09

Lucas Tieman