This program creates a FastAPI app with a dynamic greeting endpoint. Then it uses TestClient to call the endpoint with the name 'Alice' and prints the status code and JSON response.
A. The route path parameter expects an int, but 'item1' is a string
B. TestClient is not imported correctly
C. The route decorator is missing parentheses
D. The app instance is not created
Solution
Step 1: Check route parameter type
The route expects an integer item_id but the test sends 'item1' which is a string.
Step 2: Understand FastAPI's type validation
FastAPI will reject the request with a 422 error because 'item1' cannot be converted to int.
Final Answer:
The route path parameter expects an int, but 'item1' is a string -> Option A
Quick Check:
Type mismatch in path parameter causes error [OK]
Hint: Match path parameter types exactly in test URLs [OK]
Common Mistakes:
Ignoring type mismatch in path parameters
Assuming string works for int parameters
Overlooking FastAPI validation errors
5. You want to test a POST endpoint /users/ that expects JSON data {"name": "Alice"}. Which TestClient call correctly sends this data and checks for a 201 status code?
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.post("/users/")
def create_user(user: dict):
return user, 201
client = TestClient(app)
# Which call is correct?
hard
A. response = client.get("/users/", json={"name": "Alice"})
assert response.status_code == 201
B. response = client.post("/users/", json={"name": "Alice"})
assert response.status_code == 201
C. response = client.post("/users/", data="{'name': 'Alice'}")
assert response.status_code == 201
D. response = client.post("/users/", params={"name": "Alice"})
assert response.status_code == 201
Solution
Step 1: Identify correct HTTP method and data format
The endpoint expects a POST request with JSON data. Using json= sends JSON correctly.
Step 2: Check status code assertion
The endpoint returns status 201 on success, so asserting response.status_code == 201 is correct.