Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to import the FastAPI class.
FastAPI
from fastapi import [1] app = [1]()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Importing Depends instead of FastAPI
Using Request or Response instead of FastAPI
✗ Incorrect
FastAPI is the main class to create an app instance.
2fill in blank
mediumComplete the code to declare a dependency using Depends.
FastAPI
from fastapi import Depends app = FastAPI() def get_token(): return "token123" @app.get("/items") def read_items(token: str = [1](get_token)): return {"token": token}
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using Request or Response instead of Depends
Not wrapping the dependency function
✗ Incorrect
Depends is used to declare dependencies in FastAPI.
3fill in blank
hardFix the error in the dependency injection to correctly inject the database session.
FastAPI
from fastapi import Depends app = FastAPI() def get_db(): db = SessionLocal() try: yield db finally: db.close() @app.get("/users") def read_users(db: Session = [1](get_db)): return db.query(User).all()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to use Depends causes runtime errors
Using Request or Response instead of Depends
✗ Incorrect
Depends is required to inject the get_db dependency properly.
4fill in blank
hardFill both blanks to create a reusable dependency and inject it into the route.
FastAPI
from fastapi import Depends app = FastAPI() def common_parameters(q: str = None, limit: int = 10): return {"q": q, "limit": limit} @app.get("/search") def search(params: dict = [1](common_parameters)): return params if params[[2]] else {"limit": 10}
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using Request instead of Depends
Using wrong dictionary keys
✗ Incorrect
Depends injects the common_parameters dependency. The key "q" is used to check the query.
5fill in blank
hardFill all three blanks to declare a dependency with parameters and use it in a route.
FastAPI
from fastapi import Depends app = FastAPI() def pagination(skip: int = 0, limit: int = 10): return {"skip": skip, "limit": limit} @app.get("/items") def get_items(p: dict = [1](pagination)): return {"skip": p[[2]], "limit": p[[3]]}
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong keys like "page"
Not using Depends to inject the dependency
✗ Incorrect
Depends injects the pagination dependency. The keys "skip" and "limit" access pagination values.