Bird
0
0

You want to create a dependency that extracts a query parameter token and returns it. Which of these is the best way to write the dependency function and use it with Depends?

hard🚀 Application Q8 of 15
FastAPI - Dependency Injection
You want to create a dependency that extracts a query parameter token and returns it. Which of these is the best way to write the dependency function and use it with Depends?
Adef get_token(token: str): return token @app.get('/secure/') def secure_route(token: str = Depends(get_token)): return {"token": token}
Bdef get_token(): return 'fixed_token' @app.get('/secure/') def secure_route(token: str = Depends(get_token)): return {"token": token}
Cdef get_token(token: str = Query(...)): return token @app.get('/secure/') def secure_route(token: str = Depends(get_token)): return {"token": token}
Ddef get_token(): return None @app.get('/secure/') def secure_route(token: str = Depends(get_token)): return {"token": token}
Step-by-Step Solution
Solution:
  1. Step 1: Understand how to get query parameters in dependencies

    To extract query parameters in a dependency, use FastAPI's Query with a default or required value.
  2. Step 2: Check which option uses Query correctly

    def get_token(token: str = Query(...)): return token @app.get('/secure/') def secure_route(token: str = Depends(get_token)): return {"token": token} uses token: str = Query(...) to require the token from query parameters, then returns it.
  3. Final Answer:

    Option C correctly extracts query parameter using Query in dependency -> Option C
  4. Quick Check:

    Use Query(...) in dependency to get query params [OK]
Quick Trick: Use Query(...) inside dependency to get query params [OK]
Common Mistakes:
MISTAKES
  • Not using Query to declare query parameters in dependencies
  • Returning fixed or None values instead of actual query data

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes