Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

fastapi with sqlchemy, return the total count number of row of the table

  1. User

    fastapi with sqlchemy, return the total count number of row of the table

  2. Assistant

    Assuming you have a SQLAlchemy model for your table, and you're using FastAPI's SQLAlchemy dependency to work with it, you could return the total count of rows in the following way:

    from fastapi import FastAPI, Depends
    from sqlalchemy.orm import Session
    from .database import SessionLocal
    from .models import MyModel
    
    app = FastAPI()
    
    # Dependency to get a database session
    def get_db():
        try:
            db = SessionLocal()
            yield db
        finally:
            db.close()
    
    @app.get("/total_count")
    async def get_total_count(db: Session = Depends(get_db)):
        count = db.query(MyModel).count()
        return {"total_count": count}
    

    Here, we define an endpoint /total_count that returns the total count of rows in the MyModel table. We use the Depends function to get a database session, and then simply call .count() on the query for the MyModel table to get the total count.