Consider a FastAPI endpoint that expects a Pydantic model with a required integer field. What will the server respond if the client sends a string instead of an integer?
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): quantity: int @app.post("/items/") async def create_item(item: Item): return {"quantity": item.quantity}
Think about how Pydantic validates data types before the endpoint logic runs.
FastAPI uses Pydantic to validate incoming data. If the data type does not match the expected type, FastAPI returns a 422 error with details. It does not silently convert or crash.
Given a Pydantic model with a field defined as price: float, what will be the value of price if the client sends the string "12.5"?
from pydantic import BaseModel class Product(BaseModel): price: float product = Product(price="12.5") print(product.price)
Pydantic tries to convert compatible types automatically.
Pydantic converts strings that represent numbers into the correct numeric type automatically during validation.
Which model definition will cause FastAPI to reject a request missing the name field?
Consider which fields are required by default in Pydantic.
In option A, name is required because it has no default. In B, C, and D, name is optional or has a default, so missing it won't cause an error.
Given this FastAPI endpoint, why does it accept a string for age without error?
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Person(BaseModel): age: str @app.post("/person/") async def create_person(person: Person): return {"age": person.age}
Check the declared type of the field.
The field age is declared as a string, so any string input passes validation without error.
Which of the following best explains why validation is crucial in FastAPI apps?
Think about the role of validation in data safety and app stability.
Validation protects the app by ensuring data is correct before processing, which prevents crashes and security risks.