0
0
FastAPIframework~10 mins

Path operation dependencies 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 dependency 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 Request or Response instead of Depends.
Using Path instead of Depends for dependencies.
2fill in blank
medium

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

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

Fix the error in the path operation to use the dependency 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'
ADepends(get_token)
Bget_token
CDepends
Dget_token()
Attempts:
3 left
💡 Hint
Common Mistakes
Using the function name without Depends.
Calling the function directly instead of passing it to Depends.
4fill in blank
hard

Fill both blanks to declare a dependency that extracts a query parameter and use it in the path operation.

FastAPI
from fastapi import FastAPI, Depends, Query

app = FastAPI()

def get_limit(limit: int = [1]):
    return limit

@app.get("/items/")
async def read_items(limit: int = [2]):
    return {"limit": limit}
Drag options to blanks, or click blank then click option'
AQuery(10)
BDepends(get_limit)
CQuery()
DDepends(Query(10))
Attempts:
3 left
💡 Hint
Common Mistakes
Not using Query in the dependency function parameter.
Not using Depends in the path operation parameter.
5fill in blank
hard

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

FastAPI
from fastapi import FastAPI, Depends, Header, HTTPException

app = FastAPI()

def verify_token(x_token: str = [1]):
    if x_token != "fake-super-secret-token":
        raise HTTPException(status_code=401, detail="Invalid token")
    return x_token

@app.get("/secure-data")
async def secure_data(token: str = [2]):
    return {"token": [3]
Drag options to blanks, or click blank then click option'
AHeader(...)
BDepends(verify_token)
Ctoken
DHeader(None)
Attempts:
3 left
💡 Hint
Common Mistakes
Using Header(None) which makes the header optional.
Not using Depends in the path operation parameter.
Returning the wrong variable in the response.