Bird
0
0

Analyze this FastAPI dependency code:

medium📝 Debug Q6 of 15
FastAPI - Dependency Injection
Analyze this FastAPI dependency code:
from fastapi import Depends

def get_resource():
    resource = open_resource()
    return resource

def fetch_data(res = get_resource()):
    return res.read()

What is the main issue with this code?
ADependency is called at function definition, not injected per request
BMissing import for Depends
CFunction get_resource does not return anything
Dfetch_data should be async to use dependencies
Step-by-Step Solution
Solution:
  1. Step 1: Identify dependency usage

    The function fetch_data uses res = get_resource() as a default parameter, which calls get_resource immediately at definition time.
  2. Step 2: Understand dependency injection

    FastAPI expects dependencies to be declared with Depends() so they are called per request, not once at startup.
  3. Step 3: Problem

    Calling get_resource() directly means the resource is opened once globally, not per request, breaking dependency injection principles.
  4. Final Answer:

    Dependency is called at function definition, not injected per request -> Option A
  5. Quick Check:

    Dependency must be wrapped in Depends() [OK]
Quick Trick: Use Depends() to defer dependency calls per request [OK]
Common Mistakes:
MISTAKES
  • Calling dependency functions directly instead of using Depends
  • Assuming default parameters are evaluated per request
  • Ignoring the need for per-request resource management

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes