CodexBloom - Programming Q&A Platform

How to implement guide with async database queries in fastapi: getting 'nonetype' object has no attribute 'items'

πŸ‘€ Views: 3 πŸ’¬ Answers: 1 πŸ“… Created: 2025-08-22
python fastapi sqlalchemy asyncio Python

I'm following best practices but I'm learning this framework and I'm building a web application using FastAPI and SQLAlchemy, and I'm working with an behavior when trying to perform asynchronous database queries. I have a route that fetches user data and returns it as JSON, but I'm getting the behavior `AttributeError: 'NoneType' object has no attribute 'items'`. I've set up an asynchronous session using `async_session` from SQLAlchemy, but it seems like the result is sometimes returning `None` instead of a valid user object. Here’s the relevant part of my FastAPI route: ```python from fastapi import FastAPI, HTTPException 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(engine, expire_on_commit=False) app = FastAPI() @app.get('/users/{user_id}') async def get_user(user_id: int, db: AsyncSession = Depends(async_session)): result = await db.execute(select(User).where(User.id == user_id)) user = result.scalar_one_or_none() if user is None: raise HTTPException(status_code=404, detail="User not found") return user ``` I've tried using `scalar_one()` instead of `scalar_one_or_none()`, but that results in an behavior if the user doesn't exist. I also confirmed that the `user_id` being passed is valid and exists in the database. My models are correctly defined, and I’ve double-checked my database connection settings. I'm using FastAPI version 0.68.0 and SQLAlchemy 1.4.22. Can anyone suggest what might be causing the `NoneType` behavior? Could it be related to how I'm handling the session or the way I'm querying the database? This is my first time working with Python LTS. What are your experiences with this? This is for a web app running on Windows 11. What are your experiences with this?