user2136168
user2136168

Reputation: 83

Unable to override dependency in FastAPI/FastAPi-Utils

This may be a newbie question. I am not able to override the greetings message in this simple 2 files FastAPI project. Could you please tell me what I might have done wrong? Thanks a lot for your help.

greetings_service.py

from fastapi import Depends
from fastapi_utils.cbv import cbv
from fastapi_utils.inferring_router import InferringRouter


router = InferringRouter()

def get_msg():
    return "Original Message"

@cbv(router)
class GreetingsService:
    @router.get("/")
    async def greet(self, msg: str = Depends(get_msg)):
        return f"Hello from FastAPI {msg}"

main.py

from fastapi import FastAPI
from starlette.testclient import TestClient

import greetings_service

app = FastAPI()
app.include_router(greetings_service.router)

def get_new_msg():
    return "New Message"

//Tried this, doesn't work
#app.dependency_overrides["get_msg"] = get_new_msg()

//These 2 lines doesn't work too
app.dependency_overrides["get_msg"] = get_new_msg()
greetings_service.router.dependency_overrides_provider = app

client = TestClient(app)

res = client.get("/")
print(res.content) #"Hello from FastAPI Original Message" :(

Upvotes: 2

Views: 5464

Answers (1)

LearningNoob
LearningNoob

Reputation: 700

The issue is with this:

app.dependency_overrides["get_msg"] = get_new_msg()

You are passing the dependency as string instead of the actual dependency.

Something like this would work:

from fastapi import FastAPI
from starlette.testclient import TestClient

import greetings_service

app = FastAPI()
app.include_router(greetings_service.router)


def get_new_msg():
    return "New Message"


app.dependency_overrides[greetings_service.get_msg] = get_new_msg

client = TestClient(app)
res = client.get("/")
print(res.content)

Upvotes: 3

Related Questions