0
0
FastAPIframework~10 mins

Optional and nullable fields in FastAPI - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to make the 'description' field optional in a FastAPI model.

FastAPI
from typing import [1]
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    description: [1][str] = None
Drag options to blanks, or click blank then click option'
ASet
BList
COptional
DDict
Attempts:
3 left
💡 Hint
Common Mistakes
Using List or Dict instead of Optional
Not importing Optional from typing
Setting default to empty string instead of None
2fill in blank
medium

Complete the code to allow the 'price' field to be nullable (accept None) in a FastAPI model.

FastAPI
from typing import Optional
from pydantic import BaseModel

class Product(BaseModel):
    name: str
    price: Optional[[1]] = None
Drag options to blanks, or click blank then click option'
Afloat
Bstr
Cint
Dbool
Attempts:
3 left
💡 Hint
Common Mistakes
Using int instead of float for price
Not setting default to None for nullable
Using str for price
3fill in blank
hard

Fix the error in the code to correctly declare an optional nullable field 'tags' as a list of strings.

FastAPI
from typing import [1], List
from pydantic import BaseModel

class BlogPost(BaseModel):
    title: str
    tags: [1][List[str]] = None
Drag options to blanks, or click blank then click option'
ACallable
BOptional
CAny
DUnion
Attempts:
3 left
💡 Hint
Common Mistakes
Using Union without specifying None
Using Any which is too broad
Not importing Optional
4fill in blank
hard

Fill both blanks to define a FastAPI model with an optional nullable 'rating' field of type float and a required 'title' field.

FastAPI
from typing import [1]
from pydantic import BaseModel

class Review(BaseModel):
    title: str
    rating: [2][float] = None
Drag options to blanks, or click blank then click option'
AOptional
BList
CDict
DSet
Attempts:
3 left
💡 Hint
Common Mistakes
Using different types for import and annotation
Using List or Dict instead of Optional
Not setting default to None
5fill in blank
hard

Fill all three blanks to create a FastAPI model with an optional nullable 'email' field of type string, a required 'username' field, and an optional nullable 'age' field of type int.

FastAPI
from typing import [1]
from pydantic import BaseModel

class User(BaseModel):
    username: str
    email: [2][str] = None
    age: [3][int] = None
Drag options to blanks, or click blank then click option'
AOptional
BList
DDict
Attempts:
3 left
💡 Hint
Common Mistakes
Using List or Dict instead of Optional
Not setting default to None
Mixing different types for optional fields