Skip to content

Instantly share code, notes, and snippets.

@noor-ul-amin0
Created September 18, 2023 11:35
Show Gist options
  • Save noor-ul-amin0/937e6a5f81b8da08f4728a20e355b94f to your computer and use it in GitHub Desktop.
Save noor-ul-amin0/937e6a5f81b8da08f4728a20e355b94f to your computer and use it in GitHub Desktop.
FastAPI with SQLAlchemy: This Gist contains a basic setup for using FastAPI with SQLAlchemy. It includes the creation of a database engine, a session local, and a base class for declarative models. It also includes a dependency function for getting the DB session and an annotated DB dependency.
from fastapi import Depends
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session
from sqlalchemy.ext.declarative import declarative_base
from typing import Annotated
# Database URL
SQLALCHEMY_DATABASE_URL = 'Your database url'
# Create engine
engine = create_engine(SQLALCHEMY_DATABASE_URL)
# Create session local
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# Create base class for declarative models
Base = declarative_base()
# Dependency for getting DB session
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
# Annotated DB dependency
db_dependency = Annotated[Session, Depends(get_db)]
@noor-ul-amin0
Copy link
Author

Add basic SQL db setup in FastAPI

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment