Bird
Raised Fist0
FastAPIframework~20 mins

Testing path operations in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
FastAPI Path Operations Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the response status code when a GET request is made to this FastAPI path operation?

Consider this FastAPI path operation:

from fastapi import FastAPI
app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}

What status code will the response have when requesting /items/5?

FastAPI
from fastapi import FastAPI
app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}
A200
B404
C500
D302
Attempts:
2 left
💡 Hint

By default, successful GET requests return a standard success status code.

📝 Syntax
intermediate
2:00remaining
Which option correctly defines a POST path operation with a JSON body in FastAPI?

Which of the following code snippets correctly defines a POST path operation that accepts a JSON body with a name field?

A
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str

@app.post("/items")
async def create_item(item: Item):
    return item
B
from fastapi import FastAPI
app = FastAPI()

@app.post("/items")
async def create_item(name: str):
    return {"name": name}
C
from fastapi import FastAPI
app = FastAPI()

@app.post("/items")
async def create_item():
    name = request.json()["name"]
    return {"name": name}
D
from fastapi import FastAPI
app = FastAPI()

@app.post("/items")
def create_item(item: dict):
    return item
Attempts:
2 left
💡 Hint

FastAPI uses Pydantic models to parse and validate JSON bodies.

❓ state_output
advanced
2:00remaining
What is the output of this test client code for a FastAPI GET path operation?

Given this FastAPI app and test code, what will print(response.json()) output?

from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()

@app.get("/users/{user_id}")
async def get_user(user_id: int):
    return {"user_id": user_id, "name": f"User{user_id}"}

client = TestClient(app)
response = client.get("/users/10")
print(response.json())
FastAPI
from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()

@app.get("/users/{user_id}")
async def get_user(user_id: int):
    return {"user_id": user_id, "name": f"User{user_id}"}

client = TestClient(app)
response = client.get("/users/10")
print(response.json())
A{"user_id": 10, "name": "user10"}
B{"user_id": "10", "name": "User10"}
C{"user_id": 10, "name": "User10"}
DTypeError: Object of type int is not JSON serializable
Attempts:
2 left
💡 Hint

FastAPI automatically converts path parameters to the declared type and serializes the response to JSON.

🔧 Debug
advanced
2:00remaining
Which option causes a 422 Unprocessable Entity error when testing this FastAPI POST path operation?

Given this FastAPI POST path operation:

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class User(BaseModel):
    username: str
    age: int

@app.post("/users")
async def create_user(user: User):
    return user

Which test client request will cause a 422 error?

Aclient.post("/users", json={"username": "alice", "age": 30})
Bclient.post("/users", json={"username": "bob", "age": "thirty"})
Cclient.post("/users", json={"username": "carol", "age": 25})
Dclient.post("/users", json={"username": "dave", "age": 40})
Attempts:
2 left
💡 Hint

Check the data types expected by the Pydantic model.

🧠 Conceptual
expert
3:00remaining
What happens if you call a FastAPI path operation function directly instead of using TestClient?

Consider this FastAPI path operation:

from fastapi import FastAPI
app = FastAPI()

@app.get("/hello")
async def say_hello():
    return {"message": "Hello"}

What is the difference between calling await say_hello() directly in Python and calling client.get('/hello') using TestClient?

ATestClient returns the Python dict directly; calling the function returns a Response object.
BBoth return the exact same Response object with status code and headers.
CCalling the function directly raises an error because it requires a request object; TestClient works fine.
DCalling the function directly returns the Python dict; TestClient returns a Response object with JSON content and status code.
Attempts:
2 left
💡 Hint

Think about what FastAPI does to convert function return values into HTTP responses.

Practice

(1/5)
1. What is the main purpose of testing path operations in FastAPI?
easy
A. To verify that API routes respond correctly to requests
B. To improve the speed of the FastAPI server
C. To change the URL paths dynamically
D. To automatically generate API documentation

Solution

  1. Step 1: Understand path operations in FastAPI

    Path operations define how the API responds to different URLs and HTTP methods.
  2. Step 2: Identify the role of testing

    Testing ensures these routes work as expected by simulating requests and checking responses.
  3. Final Answer:

    To verify that API routes respond correctly to requests -> Option A
  4. Quick Check:

    Testing path operations = verify API routes [OK]
Hint: Testing checks if routes respond correctly to requests [OK]
Common Mistakes:
  • Confusing testing with performance optimization
  • Thinking testing changes URL paths
  • Believing testing auto-generates docs
2. Which of the following is the correct way to import the TestClient for testing FastAPI path operations?
easy
A. from fastapi.testclient import TestClient
B. from fastapi.testing import ClientTest
C. import TestClient from fastapi
D. from fastapi.client import TestClient

Solution

  1. Step 1: Recall the correct import path

    The TestClient is imported from fastapi.testclient module.
  2. Step 2: Check each option

    Only from fastapi.testclient import TestClient uses the correct module and class name.
  3. Final Answer:

    from fastapi.testclient import TestClient -> Option A
  4. Quick Check:

    Correct import = from fastapi.testclient import TestClient [OK]
Hint: TestClient is in fastapi.testclient module [OK]
Common Mistakes:
  • Using wrong module names like fastapi.client
  • Swapping class and module names
  • Incorrect import syntax
3. Given this FastAPI app and test code, what will be the test response status code?
from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()

@app.get('/hello')
def read_hello():
    return {'message': 'Hello World'}

client = TestClient(app)
response = client.get('/hello')
medium
A. 500
B. 404
C. 200
D. 403

Solution

  1. Step 1: Analyze the defined path operation

    The app defines a GET route at '/hello' that returns a JSON message.
  2. Step 2: Check the test client request

    The test client sends a GET request to '/hello', which exists, so it should succeed with status 200.
  3. Final Answer:

    200 -> Option C
  4. Quick Check:

    Existing route GET /hello = 200 [OK]
Hint: Existing GET route returns 200 status [OK]
Common Mistakes:
  • Assuming 404 because of missing route
  • Confusing status codes like 500 or 403
  • Not matching HTTP method correctly
4. Identify the error in this test code snippet for a FastAPI path operation:
from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()

@app.post('/items')
def create_item(item: dict):
    return item

client = TestClient(app)
response = client.get('/items')
print(response.status_code)
medium
A. Missing import for dict type
B. Using GET method instead of POST for /items
C. Incorrect function name create_item
D. TestClient should be created after response

Solution

  1. Step 1: Check the path operation method

    The route '/items' accepts POST requests only.
  2. Step 2: Check the test client request method

    The test client sends a GET request to '/items', which is not allowed, causing a 405 error.
  3. Final Answer:

    Using GET method instead of POST for /items -> Option B
  4. Quick Check:

    Method mismatch causes error = Using GET method instead of POST for /items [OK]
Hint: Match test request method with route method [OK]
Common Mistakes:
  • Using wrong HTTP method in test
  • Thinking function name affects routing
  • Misunderstanding import requirements
  • Creating TestClient after request
5. You want to test a FastAPI path operation that returns a list of users. Which approach correctly tests that the response contains exactly 3 users with names 'Alice', 'Bob', and 'Carol'?
hard
A. Check only the response status code is 200 without inspecting data
B. Send POST request with user data and check status code 201
C. Call the path operation function directly without TestClient
D. Use TestClient to GET the route, then assert response.json() == [{'name': 'Alice'}, {'name': 'Bob'}, {'name': 'Carol'}]

Solution

  1. Step 1: Understand the goal of testing response data

    We want to confirm the API returns exactly the expected list of users.
  2. Step 2: Choose the correct testing method

    Using TestClient to send a GET request and asserting the JSON response matches the expected list is correct.
  3. Final Answer:

    Use TestClient to GET the route, then assert response.json() == [{'name': 'Alice'}, {'name': 'Bob'}, {'name': 'Carol'}] -> Option D
  4. Quick Check:

    Test response data equality = Use TestClient to GET the route, then assert response.json() == [{'name': 'Alice'}, {'name': 'Bob'}, {'name': 'Carol'}] [OK]
Hint: Assert response.json() matches expected list exactly [OK]
Common Mistakes:
  • Testing with POST instead of GET for retrieval
  • Calling path function directly misses request context
  • Ignoring response data content in tests
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard