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?
from fastapi import FastAPI app = FastAPI() @app.get("/items/{item_id}") async def read_item(item_id: int): return {"item_id": item_id}
By default, successful GET requests return a standard success status code.
FastAPI returns status code 200 for successful GET requests unless otherwise specified.
Which of the following code snippets correctly defines a POST path operation that accepts a JSON body with a name field?
FastAPI uses Pydantic models to parse and validate JSON bodies.
Option A uses a Pydantic model to define the expected JSON body and correctly annotates the parameter.
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())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 automatically converts path parameters to the declared type and serializes the response to JSON.
The path parameter user_id is an int, so the returned JSON has user_id as an integer and the name is formatted with capital U.
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 userWhich test client request will cause a 422 error?
Check the data types expected by the Pydantic model.
Option B sends a string for age instead of an integer, causing validation to fail and a 422 error.
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?
Think about what FastAPI does to convert function return values into HTTP responses.
Calling the path operation function directly returns the raw Python return value (a dict). TestClient simulates an HTTP request and returns a Response object with status code, headers, and JSON content.