Complete the code to declare a shared dependency function.
from fastapi import Depends def get_db(): db = "database connection" try: yield db finally: print("Close connection") async def read_items(db = Depends([1])): return {"db": db}
The shared dependency function get_db is passed to Depends to inject the database connection.
Complete the code to use the shared dependency in two endpoints.
from fastapi import FastAPI, Depends app = FastAPI() def get_token(): return "token123" @app.get("/items/") async def read_items(token = Depends([1])): return {"token": token} @app.get("/users/") async def read_users(token = Depends(get_token)): return {"token": token}
The shared dependency function get_token is passed to Depends to inject the token in both endpoints.
Fix the error in the shared dependency usage.
from fastapi import Depends def common_parameters(q: str = None): return {"q": q} async def read_items(params = Depends([1])): return params
When passing a dependency function to Depends, do not call it with parentheses. Just pass the function name.
Fill both blanks to create a shared dependency with a class and use it in an endpoint.
from fastapi import Depends, FastAPI class CommonQuery: def __init__(self, q: str = None): self.q = q app = FastAPI() @app.get("/items/") async def read_items(commons: CommonQuery = Depends([1])): return {"query": commons.[2]
The class CommonQuery is passed to Depends to create a shared dependency. The attribute q holds the query string.
Fill all three blanks to create a shared dependency with a function and use it in two endpoints.
from fastapi import FastAPI, Depends app = FastAPI() def get_token_header(x_token: str = None): if x_token != "fake-super-secret-token": raise Exception("Invalid token") return x_token @app.get("/items/") async def read_items(token: str = Depends([1])): return {"token": token} @app.get("/users/") async def read_users(token: str = Depends([2])): return {"token": token} # Use the shared dependency function [3] in both endpoints
The shared dependency function get_token_header is passed to Depends in both endpoints to check the token.