I am trying to use database session in the middleware (to write metrics to the database) I am using fastapi.params.Depends in @app.middleware("http") I read this question FastAPI - dependency inside Middleware? and was using solution from this question My code: database.py from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker SQLALCHEMY_DATABASE_URL = "postgresql://username@localhost/feast_db" # Checked that psql postgresql://username@localhost/feast_db is working engine = create_engine( SQLALCHEMY_DATABASE_URL ) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base = declarative_base() Main app: from fastapi import FastAPI, HTTPException, Request, Response, status from fastapi.params import Depends from myapp.metrics_service import models, schemas from myapp.metrics_service.database import SessionLocal, engine models.Base.metadata.create_all(bind=engine) # create database table def get_db(): db = SessionLocal() try: yield db finally: db.close() def get_app(store: "feast.FeatureStore"): proto_json.patch() app = FastAPI(dependencies=[Depends(get_db)]) request_id_contextvar = contextvars.ContextVar("request_id", default=None) ... @app.middleware("http") async def log_requests(request: Request, call_next, db: Session = Depends(get_db)): response = await call_next(request) ... curr_metric = models.Metric(rqid=request_id, name="request_duration", duration_ms=total_time_ms) print("XXX_ curr_metric") db.session.add(curr_metric) db.session.commit() return response I have an error db.add(curr_metric) AttributeError: 'Depends' object has no attribute 'add' How to fix the error? Continue reading...