CodexBloom - Programming Q&A Platform

FastAPI Route With Async Function scenarios with 'RuntimeError: Event loop is closed'

👀 Views: 3 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-08
fastapi asyncio sqlalchemy Python

I'm converting an old project and Quick question that's been bugging me - Can someone help me understand I've been banging my head against this for hours....... I'm working on a personal project and I'm developing a FastAPI application and working with a `RuntimeError: Event loop is closed` behavior when trying to call an asynchronous function from within a route handler. The scenario arises under specific conditions where the handler makes simultaneous calls to multiple async database queries using SQLAlchemy's async session. Here's a simplified version of my code: ```python from fastapi import FastAPI, Depends from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String DATABASE_URL = 'postgresql+asyncpg://user:password@localhost/dbname' engine = create_async_engine(DATABASE_URL, echo=True) Base = declarative_base() class Item(Base): __tablename__ = 'items' id = Column(Integer, primary_key=True, index=True) name = Column(String, index=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.get('/items/') async def read_items(db: AsyncSession = Depends(get_db)): query1 = db.execute(select(Item)) query2 = db.execute(select(Item).filter(Item.name == 'example')) result1 = await query1.fetchall() result2 = await query2.fetchall() return {'items': result1, 'filtered': result2} ``` When I call the `/items/` endpoint, the application returns the aforementioned runtime behavior. I've checked if my database connection is correctly configured and it seems fine. I've also ensured that I'm using compatible versions of FastAPI and SQLAlchemy (FastAPI 0.68.0 and SQLAlchemy 1.4.27). Additionally, I tried running the app with `uvicorn` and `--reload` to see if that might help, but the behavior continues. What could be causing the event loop to close, and how can I resolve this scenario? Any insights or suggestions would be greatly appreciated! This is part of a larger application I'm building. Is there a better approach? My development environment is Windows. Thanks for your help in advance! This is my first time working with Python 3.10. Is there a simpler solution I'm overlooking? This is my first time working with Python LTS. What am I doing wrong? I've been using Python for about a year now. Hoping someone can shed some light on this. I'm working with Python in a Docker container on macOS. Any help would be greatly appreciated!