title: FastAPI to handle multiple DB connections via SqlAlchemy
body: <p>Can we declare multiple databases sessions in fast api like this?</p>
  <pre><code>
  Base = declarative_base()
  
  @contextmanager
  def get_db(db_type: str):
      if db_type == &quot;retention&quot;:
          db = RetentionSessionLocal()
      else:
          db = SessionLocal()
      try:
          yield db
          db.commit()
      except Exception:
          db.rollback()
          raise
      finally:
          db.close()
  </code></pre>
  <p>Where RetentionSessionLocal is pointing to different database and SessionLocal is pointing to main db.</p>
  <p>And also is declarative_base() same for any database or it have to change?</p>
  <p>And if the above is something can be done then how can we declare models to respective databases to do CRUD operations?</p>
  <hr />
  <p><strong>Update:</strong> Not using this code anymore but may be useful as it is a working code earlier handling two databases:</p>
  <pre><code>engine = create_engine(DATABASE_URL, pool_pre_ping=True)
  SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
  
  RETENTION_DATABASE_URL = &quot;postgresql+psycopg2://{0}:{1}@{2}:{3}/{4}&quot;.format(
      os.environ[&quot;DB_USERNAME&quot;],
      os.environ[&quot;DB_PASSWORD&quot;],
      os.environ[&quot;DB_HOST&quot;], &quot;5432&quot;,
      os.environ[&quot;RETENTION_DB&quot;]
  )
  retention_engine = create_engine(RETENTION_DATABASE_URL, pool_pre_ping=True)
  RetentionSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=retention_engine)
  MainBase = declarative_base()
  RetentionBase = declarative_base()
  </code></pre>