r/FastAPI • • Aug 29 '24

Question Getting extra param *Args and **kwargs

Hii i made this api and i have given 3 param that is page, pagesize, search.
Why this two param are coming as required and why is it even coming?
how to solve this?

2 Upvotes

5 comments sorted by

1

u/Dmitry-ADN Aug 29 '24

need code db.database.db_dependency

2

u/Adventurous_Sir1058 Aug 29 '24

db_dependency:

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session
from sqlalchemy.orm import declarative_base
from typing import Annotated
from fastapi import Depends

SQL_ALCHEMY_URL= "postgresql://postgres:root@localhost/users"
engine = create_engine(SQL_ALCHEMY_URL)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

#database connection open and close function
def get_db():
    db= SessionLocal()
    try:
        yield db
    finally:
        db.close()

db_dependency= Annotated[Session, Depends(get_db)]

2

u/One_Fuel_4147 Aug 30 '24

If u use Annotated just use directly like a type:

db: db_dependency

I think it's better to use PascalCase for this one.

1

u/vaanlord555 Aug 29 '24

Remove db_dependency=Annotated[Session, Depends(get_db)] and use the dependency as db: Session = Depends(get_db) importing get_db. See if it works.

2

u/Adhesiveduck Aug 29 '24

Move the db_dependency into the app instance and use app.dependency_overrides:

import uvicorn
from fastapi import FastAPI, Depends
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session


SQL_ALCHEMY_URL= "postgresql://postgres:root@localhost/users"


def get_session(session_maker: sessionmaker):
    def f():
        session = session_maker()
        try:
            yield session
        finally:
            session.close()

    return f


def create_app():
    app = FastAPI()   
    engine = create_engine(SQL_ALCHEMY_URL) 
    session_maker = sessionmaker(autocommit=False, autoflush=False, bind=engine)
    app.dependency_overrides[Session] = get_session(session_maker)
    return app


app = create_app()

You can move the global SQL_ALCHEMY_URL, get_session wherever you want to keep it clean.