question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Dependencies with optional parameters

See original GitHub issue

First check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google “How to X in FastAPI” and didn’t find any information.
  • I already read and followed all the tutorial in the docs and didn’t find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.
  • After submitting this, I commit to:
    • Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.
    • Or, I already hit the “watch” button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
    • Implement a Pull Request for a confirmed bug.

Example

Here’s a self-contained minimal, reproducible, example with my use case:

from fastapi import FastAPI, Depends

app = FastAPI()


def dependency(request: Request, check: bool = True):
    pass


@app.get("/1")
def read_root(t = Depends(dependency, check=False)):
    return {"Hello": "World"}

@app.get("/2")
def read_root(t = Depends(dependency)):
    return {"Hello": "World"}

Description

I searched the docs and didn’t find any reference of this being possible. Could this be done somehow with FastAPI today? Am I missing something?

If it is not possible today, how can this be implemented, I would gladly help with it.

Thanks!

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:17 (2 by maintainers)

github_iconTop GitHub Comments

6reactions
SirTelemakcommented, Aug 10, 2020

That’s how Depends constructor looks:

class Depends:
    def __init__(self, dependency: Callable = None, *, use_cache: bool = True):

So you can’t pass kwargs here, but there is workaround (but I can’t be sure about how good it will be working):

from fastapi import FastAPI, Depends, Request

app = FastAPI()


def dependency_factory(check: bool = True):
    def dependency(request: Request):
        if check:
            return 1
        return 2
    return dependency


@app.get("/test_overrided")
def read_root(t=Depends(dependency_factory(check=False))):
    return {"Hello": t}

@app.get("/test_default")
def read_root(t=Depends(dependency_factory())):
    return {"Hello": t}
3reactions
fgsalomoncommented, May 14, 2021

Hi, what about sub-dependencies?

For example say we have a dependency QueryChecker like on the previous examples that has an optional argument and other dependency QueryPrinter that uses the value returned by QueryChecker to do some operation.

How should we approach it?


class QueryChecker:
    def __init__(self, check: str = ""):
        self.check= check

    def __call__(self):
        if check:
            return check
        return "default_value"

class QueryPrinter:
   def __init__(self, check: str = ""):
       self.check = check

  # How can we inject the check argument?
  def __call__(self,  prefix: str = Depends(QueryChecker(check=?))  ):
        print(f"{prefix} Hello")

@app.get("/test_overrided")
def read_root(t=Depends(QueryPrinter(check="foo"))):
    return {"Hello": t}

@app.get("/test_default")
def read_root(t=Depends(QueryPrinter())):
    return {"Hello": t}
Read more comments on GitHub >

github_iconTop Results From Across the Web

Dependency Injection Optional Parameters - Stack Overflow
I have specified both parameters as optional, but my DI framework will always inject both dependencies. If I add a new action to...
Read more >
Dependency Injection and Default Parameters - Kyle Shevlin
We can solve this with a default parameter. Default parameters. JavaScript functions can be variadic, meaning they can be called with a variable ......
Read more >
Advanced Dependencies - FastAPI
Parameterized dependencies​​ All the dependencies we have seen are a fixed function or class. But there could be cases where you want to...
Read more >
Optional - Angular
Parameter decorator to be used on constructor parameters, which marks the parameter as being an optional dependency. The DI framework provides null if...
Read more >
How to Make Service Arguments/References Optional - Symfony
Sometimes, one of your services may have an optional dependency, meaning that the dependency is not required for your service to work properly....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found