How to Connect to MySQL in FastAPI: Simple Guide
To connect
FastAPI to MySQL, use SQLAlchemy with an async driver like asyncmy or aiomysql. Configure the database URL, create an async engine, and use AsyncSession to interact with the database asynchronously within your FastAPI app.Syntax
Here is the basic syntax to connect FastAPI to MySQL using SQLAlchemy with async support:
DATABASE_URL: The connection string to your MySQL database.create_async_engine: Creates an async engine for database communication.AsyncSession: Manages async database sessions.sessionmaker: Factory to create sessions.Depends: FastAPI dependency injection to provide sessions to routes.
python
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession from sqlalchemy.orm import sessionmaker from fastapi import FastAPI, Depends DATABASE_URL = "mysql+asyncmy://user:password@localhost/dbname" engine = create_async_engine(DATABASE_URL, echo=True) async_session = sessionmaker( engine, expire_on_commit=False, class_=AsyncSession ) async def get_session() -> AsyncSession: async with async_session() as session: yield session app = FastAPI()
Example
This example shows a FastAPI app connecting to MySQL asynchronously, creating a simple user table, and adding a user.
python
from fastapi import FastAPI, Depends from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession from sqlalchemy.orm import sessionmaker, declarative_base from sqlalchemy import Column, Integer, String DATABASE_URL = "mysql+asyncmy://user:password@localhost/testdb" engine = create_async_engine(DATABASE_URL, echo=True) async_session = sessionmaker(engine, expire_on_commit=False, class_=AsyncSession) Base = declarative_base() class User(Base): __tablename__ = "users" id = Column(Integer, primary_key=True, index=True) name = Column(String(50)) async def get_session() -> AsyncSession: async with async_session() as session: yield session app = FastAPI() @app.on_event("startup") async def startup(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) @app.post("/users/") async def create_user(name: str, session: AsyncSession = Depends(get_session)): new_user = User(name=name) session.add(new_user) await session.commit() await session.refresh(new_user) return {"id": new_user.id, "name": new_user.name}
Output
POST /users/ with JSON {"name": "Alice"} returns {"id": 1, "name": "Alice"}
Common Pitfalls
- Using synchronous MySQL drivers like
mysqlclientorpymysqlwith async code causes blocking and errors. - For async support, use drivers like
asyncmyoraiomysqlwith the correct SQLAlchemy URL prefixmysql+asyncmy://ormysql+aiomysql://. - Not using
AsyncSessionand mixing sync sessions leads to runtime errors. - Forgetting to
awaitasync calls likesession.commit()causes unexpected behavior.
python
## Wrong way (sync driver with async code): # DATABASE_URL = "mysql+pymysql://user:password@localhost/db" # engine = create_async_engine(DATABASE_URL) # This will fail ## Right way (async driver): # DATABASE_URL = "mysql+asyncmy://user:password@localhost/db" # engine = create_async_engine(DATABASE_URL) ## Wrong session usage: # session = Session(engine) # sync session in async code ## Right session usage: # async_session = sessionmaker(engine, class_=AsyncSession) # async with async_session() as session: # await session.commit()
Quick Reference
Summary tips for connecting FastAPI to MySQL:
- Use
asyncmyoraiomysqlfor async MySQL drivers. - Set
DATABASE_URLwith prefixmysql+asyncmy://ormysql+aiomysql://. - Create async engine with
create_async_engine. - Use
AsyncSessionfromsqlalchemy.ext.asyncio. - Always
awaitasync database calls. - Use FastAPI
Dependsto inject sessions into routes.
Key Takeaways
Use async MySQL drivers like asyncmy or aiomysql with SQLAlchemy for FastAPI.
Create an async engine and AsyncSession to handle database operations asynchronously.
Always await async calls like session.commit() to avoid errors.
Inject database sessions into FastAPI routes using Depends for clean code.
Avoid mixing synchronous drivers or sessions in async FastAPI apps.