📖 Scenario: You are building a simple FastAPI application that manages a list of tasks. To make sure your app works correctly and reliably, you will write tests that check the main features.
🎯 Goal: Create a FastAPI app with a list of tasks, add a configuration for a minimum task length, implement a route to add tasks only if they meet the length requirement, and write a test to verify this behavior.
📋 What You'll Learn
Create a list called tasks with initial tasks
Add a variable MIN_TASK_LENGTH to set the minimum allowed length for a task
Write a POST route /add-task that adds a task only if it meets the minimum length
Write a test function using TestClient to check that short tasks are rejected and valid tasks are added
💡 Why This Matters
🌍 Real World
Testing ensures that your web app works correctly every time you change code. This prevents bugs from reaching users and keeps your app reliable.
💼 Career
Writing tests is a key skill for software developers. It shows you can build stable, maintainable applications that companies trust.
Progress0 / 4 steps
1
DATA SETUP: Create the initial tasks list
Create a list called tasks with these exact string entries: 'buy milk', 'read book', and 'write code'.
FastAPI
Hint
Use a Python list with the exact task strings inside square brackets.
2
CONFIGURATION: Add minimum task length variable
Add a variable called MIN_TASK_LENGTH and set it to the integer 5.
FastAPI
Hint
Just create a variable with the exact name and value.
3
CORE LOGIC: Create POST route to add tasks with length check
Write a POST route /add-task that accepts a JSON body with a task string. Add the task to the tasks list only if its length is greater than or equal to MIN_TASK_LENGTH. Return {'success': True} if added, else {'success': False, 'error': 'Task too short'}.
FastAPI
Hint
Use @app.post decorator and async function with request.json() to get the task.
4
COMPLETION: Write a test to verify task addition logic
Import TestClient from fastapi.testclient. Create a test function called test_add_task() that uses TestClient(app) to post a short task 'eat' and check the response JSON has 'success': False. Then post a valid task 'exercise' and check the response JSON has 'success': True.
FastAPI
Hint
Use TestClient to simulate POST requests and assert to check responses.
Practice
(1/5)
1. Why is testing important for a FastAPI application?
easy
A. It helps find bugs early and ensures the app works as expected.
B. It makes the app run faster in production.
C. It automatically deploys the app to the server.
D. It changes the app's user interface without coding.
Solution
Step 1: Understand the purpose of testing
Testing is done to check if the app behaves correctly and to catch errors early.
Step 2: Compare options with testing goals
Only It helps find bugs early and ensures the app works as expected. matches the goal of testing by finding bugs and ensuring expected behavior.
Final Answer:
It helps find bugs early and ensures the app works as expected. -> Option A
Quick Check:
Testing = Find bugs early and ensure correctness [OK]
Hint: Testing finds bugs early and checks app behavior [OK]
Common Mistakes:
Thinking testing speeds up the app
Confusing testing with deployment
Believing testing changes UI automatically
2. Which of the following is the correct way to import TestClient in FastAPI for testing?
easy
A. import testclient from fastapi.testing
B. import TestClient from fastapi
C. from fastapi import TestClient
D. from fastapi.testclient import TestClient
Solution
Step 1: Recall FastAPI testing import syntax
FastAPI provides TestClient in the fastapi.testclient module.
Step 2: Match correct import statement
from fastapi.testclient import TestClient correctly imports TestClient from fastapi.testclient. Others are invalid syntax or wrong modules.
Final Answer:
from fastapi.testclient import TestClient -> Option D
Quick Check:
Correct import = from fastapi.testclient import TestClient [OK]
Hint: TestClient is in fastapi.testclient module [OK]
Common Mistakes:
Using wrong import syntax
Importing from fastapi directly
Using lowercase module names incorrectly
3. Given this FastAPI test code, what will be the output of print(response.status_code)?
A. The path parameter expects an int, but 'abc' is a string causing a validation error.
B. The endpoint URL is missing a slash.
C. TestClient is not imported correctly.
D. The function read_item does not return a dictionary.
Solution
Step 1: Check the path parameter type and request URL
The endpoint expects an integer for item_id, but the test sends 'abc' which is a string.
Step 2: Understand FastAPI validation behavior
FastAPI will reject the request with a 422 Unprocessable Entity error due to type mismatch.
Final Answer:
The path parameter expects an int, but 'abc' is a string causing a validation error. -> Option A
Quick Check:
Type mismatch in path parameter causes validation error [OK]
Hint: Check parameter types match URL values [OK]
Common Mistakes:
Ignoring type mismatch in path parameters
Assuming missing slash causes error
Thinking TestClient import is wrong
5. You want to ensure your FastAPI app reliably returns a JSON with a 'status' key set to 'ok' for the root endpoint. Which test code snippet correctly verifies this behavior?
hard
A. response = client.get("/status")
assert response.json() == {"status": "ok"}
B. response = client.post("/")
assert response.status_code == 404
C. response = client.get("/")
assert response.json() == {"status": "ok"}
D. response = client.get("/")
assert response.text == "status: ok"
Solution
Step 1: Identify the correct HTTP method and endpoint
The root endpoint "/" is usually accessed with GET to check status.
Step 2: Verify the response JSON content
response = client.get("/")
assert response.json() == {"status": "ok"} correctly sends GET to "/" and asserts the JSON response matches {"status": "ok"}.