
Module 2 Exercises: Mastering the Foundations
Practical exercises to consolidate your knowledge of Python type hints, async/await, and RESTful API design.
Module 2 Exercises: Mastering the Foundations
You've covered a lot of ground in this module: the logic of Async, the precision of Type Hints, and the language of REST. Now, let's put it all together.
Exercise 1: Refactoring to Type Hints
Take the following legacy Python function and refactor it to use Type Hints. Requirement: The function takes a list of integers and returns their average as a float.
# Refactor this
def calculate_average(numbers):
total = sum(numbers)
return total / len(numbers)
Exercise 2: Debugging the "Thread Block"
Look at the code below. If 1,000 users call the /heavy-task endpoint at once, what will happen to the server's ability to handle other requests? How would you fix it?
import time
from fastapi import FastAPI
app = FastAPI()
@app.get("/heavy-task")
async def heavy_task():
# Simulate a network request to an external API
time.sleep(2)
return {"message": "Task complete"}
Exercise 3: The REST Designer
You are designing an API for a Fitness App. Map out the Method, URL, and Expected Status Code (on success) for the following actions:
- Getting a list of all user workouts.
- Logging a brand new workout.
- Updating a user's weight (partial update).
- Deleting an old workout entry.
Self-Correction / Discussion
Exercise 1 Answer:
from typing import List
def calculate_average(numbers: List[int]) -> float:
total = sum(numbers)
return total / len(numbers)
Exercise 2 Answer:
The server will block. Even though the function is async, time.sleep is synchronous. It will hold the event loop hostage for 2 seconds. No other requests can be handled during this time.
The Fix: Use await asyncio.sleep(2) OR define the function as a standard def heavy_task() (FastAPI will then run it in a separate thread pool automatically, though asyncio is preferred for I/O).
Exercise 3 Answer:
- GET
/workouts->200 OK - POST
/workouts->201 Created - PATCH
/users/me/weight->200 OK - DELETE
/workouts/{id}->204 No Content(common for deletes) or200 OK.
Summary of Module 2
You now have the "Language" of FastAPI under your belt. You understand:
- How Type Hints power validation.
- Why Async is critical for concurrency.
- How REST principles architecture your communication.
Well done! In Module 3: FastAPI Project Structure, we will finally stop talking theory and start building the skeleton of a production-ready application.