Consider this FastAPI Pydantic model:
from pydantic import BaseModel
from typing import Optional
class Item(BaseModel):
name: str
description: Optional[str] = None
If you send a POST request with JSON {"name": "Book"}, what will be the value of description in the parsed Item?
from pydantic import BaseModel from typing import Optional class Item(BaseModel): name: str description: Optional[str] = None item = Item(name="Book") print(item.description)
Optional fields with a default value are set to that default if missing.
The description field is optional and defaults to None. If the JSON omits it, Pydantic sets it to None without error.
In FastAPI, you want a field comment that can be None or a string. Which of these definitions is correct?
Use Optional with a default None to allow null values.
Option A correctly uses Optional[str] with a default None. Option A is invalid because str cannot be assigned None without Optional. Option A is valid Python 3.10+ but lacks default value, so field is required. Option A lacks default value, so field is required.
Given this FastAPI endpoint:
from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional
app = FastAPI()
class User(BaseModel):
username: str
bio: Optional[str] = None
@app.post("/users")
async def create_user(user: User):
return {"username": user.username, "bio": user.bio or "No bio provided"}
If you POST {"username": "alice", "bio": null}, what is the JSON response?
Check how user.bio or "No bio provided" works when bio is None.
The bio field is None because JSON null maps to Python None. The expression user.bio or "No bio provided" evaluates to the string because None is falsy.
Consider this Pydantic model:
from pydantic import BaseModel
class Product(BaseModel):
name: str
price: float
description: str = None
When sending JSON {"name": "Pen", "price": 1.5, "description": null}, a validation error occurs. Why?
Check the type of description and how Pydantic treats default values.
The field description is typed as str but has a default None. This means it is not Optional and does not accept null. To accept null, it should be typed as Optional[str].
In FastAPI, what is the difference between a missing optional field and a field explicitly set to null in the JSON request body?
Think about how Pydantic treats defaults and null values.
When a field is missing, Pydantic uses the default value if provided. When a field is present with null, it maps to Python None if the type allows it (e.g., Optional). Otherwise, it raises a validation error.