0
0
FastAPIframework~10 mins

Depends function basics in FastAPI - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the Depends function from FastAPI.

FastAPI
from fastapi import [1]
Drag options to blanks, or click blank then click option'
AResponse
BRequest
CDepends
DPath
Attempts:
3 left
💡 Hint
Common Mistakes
Importing Depends from fastapi.security instead of fastapi
Using Request or Response instead of Depends
2fill in blank
medium

Complete the code to declare a dependency function that returns a fixed string.

FastAPI
def get_token():
    return [1]
Drag options to blanks, or click blank then click option'
A'token123'
B12345
Ctoken123
D"token123"
Attempts:
3 left
💡 Hint
Common Mistakes
Returning an unquoted string which causes a NameError
Returning a number instead of a string
3fill in blank
hard

Fix the error in the FastAPI path operation to use Depends correctly.

FastAPI
from fastapi import FastAPI, Depends

app = FastAPI()

def get_token():
    return "token123"

@app.get("/items/")
async def read_items(token: str = [1]):
    return {"token": token}
Drag options to blanks, or click blank then click option'
Aget_token()
BDepends(get_token)
CDepends(get_token())
Dget_token
Attempts:
3 left
💡 Hint
Common Mistakes
Calling the dependency function inside Depends
Passing the function without Depends
4fill in blank
hard

Fill both blanks to create a dependency that extracts a query parameter named 'q'.

FastAPI
from fastapi import Query

def get_query(q: str = [1]):
    return q

@app.get("/search")
async def search(query: str = [2]):
    return {"query": query}
Drag options to blanks, or click blank then click option'
AQuery(None)
BDepends(get_query)
CQuery(...)
DDepends(Query)
Attempts:
3 left
💡 Hint
Common Mistakes
Using Depends(Query) which is invalid
Using Query(None) which makes the parameter optional
5fill in blank
hard

Fill all three blanks to create a dependency that reads a header and uses it in a path operation.

FastAPI
from fastapi import Header, Depends

async def get_user_agent(user_agent: str = [1]):
    return user_agent

@app.get("/info")
async def info(agent: str = [2]):
    return {"User-Agent": [3]
Drag options to blanks, or click blank then click option'
AHeader(None)
BDepends(get_user_agent)
Cagent
DHeader(...)
Attempts:
3 left
💡 Hint
Common Mistakes
Using Header(None) which makes the header optional
Returning the wrong variable name in the response