3

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" :(

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Actually, for me it worked when I changed the dependency to string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.