title: What is the best approach to hooking up database in FastAPI?
body: <p>I found two approaches to working with databases in FastAPI. Are there any fundamental differences? if so which approach is preferable?</p>
  <p><strong>Approach 1</strong>
  This is found in official FastAPI-fullstack  <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql/blob/master/%7B%7Bcookiecutter.project_slug%7D%7D/backend/app/app/api/deps.py" rel="nofollow noreferrer">example</a> :</p>
  <pre class="lang-py prettyprint-override"><code>from fastapi import Depends
  from sqlalchemy.orm import sessionmaker
  from sqlalchemy import create_engine
  
  engine = create_engine(SQLALCHEMY_DATABASE_URI, pool_pre_ping=True)
  SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
  
  def get_db() -&gt; Generator:
      try:
          db = SessionLocal()
          yield db
      finally:
          db.close()
  
  
  def get_current_user(
      db: Session = Depends(get_db), token: str = Depends(reusable_oauth2)
  ) -&gt; models.User:
      ...
  
  </code></pre>
  <p><strong>Approach 2</strong>
  Following approach found in official <a href="https://fastapi.tiangolo.com/advanced/async-sql-databases/" rel="nofollow noreferrer">FastAPI docs</a>, some blogs and also in <code>fastapi_users</code> package documentation:</p>
  <pre class="lang-py prettyprint-override"><code>import databases
  
  DATABASE_URL = &quot;sqlite:///./test.db&quot;
  database = databases.Database(DATABASE_URL)
  
  @app.on_event(&quot;startup&quot;)
  async def startup():
      await database.connect()
  
  
  @app.on_event(&quot;shutdown&quot;)
  async def shutdown():
      await database.disconnect()
  
  </code></pre>
  <p><strong>Edit (2021-09-06) - Approach 3</strong></p>
  <p>Another way recommended in the new SQLModel package docs by tiangolo himself. This seems like just a variant of the first approach above, but for sake of completeness:</p>
  <p><a href="https://sqlmodel.tiangolo.com/tutorial/fastapi/session-with-dependency/" rel="nofollow noreferrer">https://sqlmodel.tiangolo.com/tutorial/fastapi/session-with-dependency/</a></p>
  <pre><code>sqlite_file_name = &quot;database.db&quot;
  sqlite_url = f&quot;sqlite:///{sqlite_file_name}&quot;
  
  connect_args = {&quot;check_same_thread&quot;: False}
  engine = create_engine(sqlite_url, echo=True, connect_args=connect_args)
  
  def get_session():
      with Session(engine) as session:
          yield session
  
  # Code here omitted 
  
  @app.post(&quot;/heroes/&quot;, response_model=HeroRead)
  def create_hero(*, session: Session = Depends(get_session), hero: HeroCreate):
      db_hero = Hero.from_orm(hero)
      session.add(db_hero)
      session.commit()
      session.refresh(db_hero)
      return db_hero
  
  </code></pre>