Skip to content

Added Documentation for usage with async tools. Fixes #626#633

Closed
deshetti wants to merge 3 commits into
fastapi:mainfrom
deshetti:main
Closed

Added Documentation for usage with async tools. Fixes #626#633
deshetti wants to merge 3 commits into
fastapi:mainfrom
deshetti:main

Conversation

@deshetti

@deshetti deshetti commented Aug 8, 2023

Copy link
Copy Markdown

I have spent a good amount of time to figure out async implementation with SQLModel & FastAPI in one of our projects and thought this would be a helpful guide for anyone who is looking to do the same in their projects.

A simple working project is available here to test. Running the docker-compose will start the postgres with the required database: https://github.com/deshetti/sqlmodel-async-example

@github-actions

github-actions Bot commented Aug 8, 2023

Copy link
Copy Markdown
Contributor

📝 Docs preview for commit a5fe1d1 at: https://ececea1e.sqlmodel.pages.dev

@github-actions

github-actions Bot commented Aug 9, 2023

Copy link
Copy Markdown
Contributor

📝 Docs preview for commit b0081f5 at: https://049f644f.sqlmodel.pages.dev

@tiangolo tiangolo added the docs Improvements or additions to documentation label Oct 22, 2023
```

## Final code
```

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
```
```python

Comment on lines +15 to +17
```
pip install sqlmodel asyncpg fastapi uvicorn
```

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
```
pip install sqlmodel asyncpg fastapi uvicorn
```
```bash
pip install sqlmodel asyncpg fastapi uvicorn

)


# Ayschronous Context manager for handling database sessions

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
# Ayschronous Context manager for handling database sessions
# Asynchronous Context manager for handling database sessions

@StashOfCode

StashOfCode commented Feb 8, 2024

Copy link
Copy Markdown

@tiangolo , are you merging this in this century or next?

@moralespanitz

Copy link
Copy Markdown

@tiangolo Why don't you add the contribution?

@vduseev

vduseev commented Jul 11, 2024

Copy link
Copy Markdown

Interesting approach. Why not use async_sessionmaker?

@Lexachoc

Lexachoc commented Jul 11, 2024

Copy link
Copy Markdown

The async session part doesn't work for me and gives an error when executing statement.

https://github.com/deshetti/sqlmodel-async-example/blob/e412da00f557a352ee3f66a8545ef11401ea5dde/main.py#L42-L47

# Ayschronous Context manager for handling database sessions
@asynccontextmanager
async def get_session() -> AsyncSession:
    async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
    async with async_session() as session:
        yield session

error occurs at:
results= await session.exec(statement)

within an endpoint where the session is a dependency: session: AsyncSession = Depends(get_session)

error message: '_AsyncGeneratorContextManager' object has no attribute 'exec'

Also, there is a warning in Pycharm that says:
Unexpected type(s): (Any, Type[AsyncSession], bool) Possible type(s): (Connection | Connection | Engine | Engine | None, None, bool) (Connection | Connection | Engine | Engine | AsyncConnection | AsyncConnection | AsyncEngine | AsyncEngine | None, Type[_TSessionMakerType], bool) (Connection | Connection | Engine | Engine | None, None, bool) (Connection | Connection | Engine | Engine | None, Type[_TSessionMakerType], bool)
for the sessionmaker

To overcome this, I use directly the AsyncSession instead of sessionmaker:

async def get_session() -> AsyncSession:
    async with AsyncSession(data_engine) as session:
        yield session

which works for me when using the async session as dependencies.

Hope this helps others or do you have an idea why the original solution doesn't work?

This seems to be the reason for the error or is related to it: fastapi/fastapi#9054 (comment)

version:
FastAPI: 0.111.0
sqlmodel: 0.0.19
But this already happens with older versions, even if I use the latest version.

# Endpoint to create a new user
@app.post("/users/", response_model=User)
async def create_user_endpoint(user: UserCreate):
db_user = User(**user.dict())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

.dict() is deprecated for model_dump()

Suggested change
db_user = User(**user.dict())
db_user = User(**user.model_dump())

```python
@app.post("/users/", response_model=User)
async def create_user_endpoint(user: UserCreate):
db_user = User(**user.dict())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

.dict() is deprecated for model_dump()

Suggested change
db_user = User(**user.dict())
db_user = User(**user.model_dump())

Comment on lines +88 to +92
@app.post("/users/", response_model=User)
async def create_user_endpoint(user: UserCreate):
db_user = User(**user.dict())
result = await create_user(db_user)
return result

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe drop the create_user() function and just have everything in here. We also get the added benefit of showing of dependency injection, we are in the advanced section after all.

Suggested change
@app.post("/users/", response_model=User)
async def create_user_endpoint(user: UserCreate):
db_user = User(**user.dict())
result = await create_user(db_user)
return result
@app.post("/users/", response_model=User)
async def create_user_endpoint(
user: UserCreate,
session: AsyncSession = Depends(get_session),
):
db_user = User(user.model_dump())
session.add(db_user)
await session.commit()
await session.refresh(db_user)
return db_user

@zuoc1993

zuoc1993 commented Dec 5, 2024

Copy link
Copy Markdown

When will this be released?


from fastapi import FastAPI
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can use

class AsyncSession(_AsyncSession):
instead of SQLAlchemy's

@github-actions

github-actions Bot commented Sep 5, 2025

Copy link
Copy Markdown
Contributor

This pull request has a merge conflict that needs to be resolved.

@github-actions github-actions Bot added the conflicts Automatically generated when a PR has a merge conflict label Sep 5, 2025

@svlandeg svlandeg left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @deshetti, all,

Thanks for the contribution 🙏

We've discussed this internally and decided that we prefer to write the first draft of this new documentation section ourselves. We are now tracking this on our internal TODO list. We'll go ahead and close this one in the meantime.

@svlandeg svlandeg closed this May 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

conflicts Automatically generated when a PR has a merge conflict docs Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.