CodexBloom - Programming Q&A Platform

Issues with Async/Await in FastAPI when Interacting with a PostgreSQL Database

👀 Views: 0 💬 Answers: 1 📅 Created: 2025-09-06
fastapi asyncio sqlalchemy postgresql Python

I need some guidance on I tried several approaches but none seem to work. I'm encountering an issue when using async/await in my FastAPI application while trying to interact with a PostgreSQL database using SQLAlchemy. The application throws an `asyncpg.exceptions.PostgresError` with the message "cannot execute query in a transaction unless it is allowed by the current state". I've set up an async database session with `async_sessionmaker`, and my code looks like this: ```python from fastapi import FastAPI, Depends from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker from sqlalchemy.orm import sessionmaker DATABASE_URL = 'postgresql+asyncpg://user:password@localhost/dbname' engine = create_async_engine(DATABASE_URL, echo=True) async_session = async_sessionmaker(bind=engine, expire_on_commit=False) app = FastAPI() async def get_db() -> AsyncSession: async with async_session() as session: yield session @app.post('/items/') async def create_item(item: ItemCreate, db: AsyncSession = Depends(get_db)): new_item = Item(**item.dict()) db.add(new_item) await db.commit() # This line raises the error await db.refresh(new_item) return new_item ``` I've double-checked the connection string and the database is up and running. I also ensured that the version of SQLAlchemy I am using is 1.4.22, which supports async operations. Could the issue be related to how the transaction is being handled? I’ve tried using `begin` and `commit` explicitly in a context manager, but it didn't resolve the problem. Any insights on how to fix this would be greatly appreciated! For context: I'm using Python on Ubuntu 22.04. What am I doing wrong? What are your experiences with this?