Bird
Raised Fist0
FastAPIframework~20 mins

Optional and nullable fields in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
FastAPI Optional Fields Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output when sending a JSON with missing optional field?

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?

FastAPI
from pydantic import BaseModel
from typing import Optional

class Item(BaseModel):
    name: str
    description: Optional[str] = None

item = Item(name="Book")
print(item.description)
AMissing attribute error
BNone
CRaises a validation error
DEmpty string ''
Attempts:
2 left
💡 Hint

Optional fields with a default value are set to that default if missing.

📝 Syntax
intermediate
2:00remaining
Which code correctly defines a nullable string field in Pydantic?

In FastAPI, you want a field comment that can be None or a string. Which of these definitions is correct?

Acomment: Optional[str] = None
Bcomment: str = None
Ccomment: str | None
Dcomment: Optional[str]
Attempts:
2 left
💡 Hint

Use Optional with a default None to allow null values.

❓ state_output
advanced
2:00remaining
What is the output of this FastAPI endpoint with nullable field?

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?

A{"username": "alice", "bio": ""}
B{"username": "alice", "bio": null}
CValidation error because bio is null
D{"username": "alice", "bio": "No bio provided"}
Attempts:
2 left
💡 Hint

Check how user.bio or "No bio provided" works when bio is None.

🔧 Debug
advanced
2:00remaining
Why does this FastAPI model raise a validation error on null input?

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?

ABecause name is missing a default value
BBecause price cannot be float with decimal
CBecause description is typed as str but default None does not allow null
DBecause null is not valid JSON
Attempts:
2 left
💡 Hint

Check the type of description and how Pydantic treats default values.

🧠 Conceptual
expert
3:00remaining
How does FastAPI handle missing vs null fields in request bodies?

In FastAPI, what is the difference between a missing optional field and a field explicitly set to null in the JSON request body?

AMissing optional fields get default values; null fields map to None if type allows it
BBoth missing and null fields cause validation errors
CMissing fields are ignored; null fields are converted to empty strings
DMissing fields are set to None; null fields cause validation errors
Attempts:
2 left
💡 Hint

Think about how Pydantic treats defaults and null values.

Practice

(1/5)
1. In FastAPI, what does it mean when a field is declared as Optional[str] in a request model?
easy
A. The field is required and cannot be None.
B. The field must always be provided with a string value.
C. The field can only be an empty string but not None.
D. The field can be omitted or set to None in the request.

Solution

  1. Step 1: Understand Optional type in FastAPI

    Optional[str] means the field can be missing or have a value of type str or None.
  2. Step 2: Interpret the meaning for API requests

    This allows clients to omit the field or explicitly send null (None) as its value.
  3. Final Answer:

    The field can be omitted or set to None in the request. -> Option D
  4. Quick Check:

    Optional[str] = omitted or None [OK]
Hint: Optional means field can be missing or None [OK]
Common Mistakes:
  • Thinking Optional means field is always required
  • Confusing Optional with default values
  • Assuming Optional forbids None
2. Which of the following is the correct way to declare a nullable string field in a FastAPI Pydantic model?
easy
A. name: Optional[str] = None
B. name: str | None = None
C. name: str = None
D. name: str?

Solution

  1. Step 1: Recall Pydantic syntax for optional and nullable fields

    To allow a field to be nullable and optional, use Optional[str] with a default None.
  2. Step 2: Check each option

    A is invalid because just assigning None to str without Optional is not correct. B is valid Python 3.10+ syntax but C is the recommended explicit way in FastAPI. D is invalid syntax.
  3. Final Answer:

    name: Optional[str] = None -> Option A
  4. Quick Check:

    Nullable string = Optional[str] = None [OK]
Hint: Use Optional[type] with = None for nullable fields [OK]
Common Mistakes:
  • Using just type with = None without Optional
  • Using invalid syntax like str?
  • Confusing Optional with just default values
3. Given this FastAPI model:
from typing import Optional
from pydantic import BaseModel

class User(BaseModel):
    name: str
    nickname: Optional[str] = None

user = User(name='Alice')

What will be the value of user.nickname?
medium
A. '' (empty string)
B. 'Alice'
C. None
D. Raises an error

Solution

  1. Step 1: Analyze the model fields and defaults

    The nickname field is Optional[str] with a default of None, so if not provided, it defaults to None.
  2. Step 2: Check the instance creation

    When creating user with only name='Alice', nickname is not set, so it uses the default None.
  3. Final Answer:

    None -> Option C
  4. Quick Check:

    Optional field missing = None [OK]
Hint: Missing optional field defaults to None [OK]
Common Mistakes:
  • Assuming nickname defaults to empty string
  • Thinking nickname copies name value
  • Expecting an error for missing optional field
4. What is wrong with this FastAPI model declaration?
from typing import Optional
from pydantic import BaseModel

class Item(BaseModel):
    description: Optional[str]
medium
A. Optional[str] is not allowed in Pydantic models.
B. Missing default value for Optional field causes validation error.
C. Field description must be declared as str, not Optional[str].
D. No import for Optional is present.

Solution

  1. Step 1: Understand Optional fields in Pydantic

    Optional means the field can be None or missing, but Pydantic requires a default value for optional fields.
  2. Step 2: Check the model declaration

    The field description is Optional[str] but has no default value, so Pydantic will expect it to be provided and raise an error if missing.
  3. Final Answer:

    Missing default value for Optional field causes validation error. -> Option B
  4. Quick Check:

    Optional fields need default values [OK]
Hint: Optional fields must have default values [OK]
Common Mistakes:
  • Omitting default None for Optional fields
  • Thinking Optional alone makes field optional
  • Ignoring Pydantic validation rules
5. You want to create a FastAPI model where the field email can be omitted, but if present, it can be set to null explicitly. Which is the best way to declare this field?
hard
A. email: Optional[str] = None
B. email: str = None
C. email: str | None
D. email: Optional[str]

Solution

  1. Step 1: Understand requirements for the field

    The field must be optional (can be omitted) and nullable (can be None explicitly).
  2. Step 2: Evaluate each declaration

    B lacks Optional and default None, so it is not optional. C lacks default None, so field is required. D lacks default None, so field is required. A uses Optional[str] with default None, making it optional and nullable.
  3. Final Answer:

    email: Optional[str] = None -> Option A
  4. Quick Check:

    Optional with default None = optional and nullable [OK]
Hint: Use Optional[type] with = None for optional nullable fields [OK]
Common Mistakes:
  • Forgetting to assign default None
  • Using union without default value
  • Assuming Optional alone makes field optional
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