Practice & Assessment
Test your understanding of Async Programming and Dependencies
Multiple Choice Questions
5A FastAPI route uses `async def` but calls `time.sleep(5)` inside. What is the consequence?
What does `Depends()` with no argument do when used as a type annotation default?
In a yield dependency, when does the code after `yield` execute?
Which task type is NOT appropriate for FastAPI's BackgroundTasks?
A dependency `A` depends on dependency `B`. FastAPI calls both for the same request. How many times is `B` called by default?
Coding Challenges
1Async URL Shortener with Background Logging
Build an async FastAPI app that shortens URLs. Store mappings in a dict. Implement: POST `/shorten` accepting `{url: str}` that validates the URL starts with `http`, generates a 6-character random code, stores the mapping, and schedules a background task to append `{code}: {url}` to a `logs.txt` file. GET `/r/{code}` should return the original URL or 404. Use `async def` and `httpx.AsyncClient` to HEAD the original URL to verify it is reachable before shortening (return 400 if not). Inputs: valid/invalid URLs. Outputs: `{code}`, original URL, or appropriate errors. Estimated time: 25 minutes.
Mini Project
Task Management API with Dependency Injection
Build a Task Management API demonstrating all module concepts. Define a `Task` model with `id`, `title`, `description`, `status` (enum: todo/in_progress/done), `priority` (1-5), `assigned_to` (optional str), and `created_at`. Create a `CommonFilters` class-based dependency resolving `status`, `priority`, and `skip/limit` from query params. Create a `get_db` yield dependency simulating a DB session (use a dict). Implement async routes: GET `/tasks/` using `CommonFilters`, POST `/tasks/` returning 201 and scheduling a background task to log creation, GET `/tasks/{id}` with 404, PATCH `/tasks/{id}/status` to advance status, DELETE `/tasks/{id}` with 204. All routes must use `async def` where appropriate, chain dependencies correctly, and demonstrate teardown in the yield dependency.
