Bird
Raised Fist0
FastAPIframework~20 mins

Field types and constraints in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
FastAPI Field Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this FastAPI endpoint with constrained fields?
Consider this FastAPI model and endpoint. What will be the response when sending {"age": 25, "name": "Anna"}?
FastAPI
from fastapi import FastAPI
from pydantic import BaseModel, Field

app = FastAPI()

class User(BaseModel):
    name: str = Field(min_length=3, max_length=10)
    age: int = Field(gt=18, lt=30)

@app.post("/user")
async def create_user(user: User):
    return {"message": f"User {user.name} aged {user.age} created"}
A422 Unprocessable Entity error due to name length
B422 Unprocessable Entity error due to age constraint
C{"message": "User Anna aged 25 created"}
D500 Internal Server Error
Attempts:
2 left
💡 Hint
Check the constraints on name and age fields carefully.
📝 Syntax
intermediate
1:30remaining
Which option correctly defines a constrained string field in FastAPI?
You want a string field 'title' that must be at least 5 characters and at most 20 characters. Which code snippet is correct?
Atitle: str = Field(size=(5,20))
Btitle: str = Field(length=(5,20))
Ctitle: str = Field(min=5, max=20)
Dtitle: str = Field(min_length=5, max_length=20)
Attempts:
2 left
💡 Hint
Look for the correct parameter names for string length constraints in Pydantic Field.
🔧 Debug
advanced
2:00remaining
Why does this FastAPI model raise a validation error for input {"score": 101}?
Given this model, why does sending {"score": 101} cause a validation error?
FastAPI
from pydantic import BaseModel, Field

class Result(BaseModel):
    score: int = Field(ge=0, le=100)
ABecause score must be a string, not an int
BBecause 101 is greater than the maximum allowed value 100
CBecause Field does not support ge and le parameters
DBecause 101 is less than the minimum allowed value 0
Attempts:
2 left
💡 Hint
Check the meaning of ge and le parameters in Field.
❓ state_output
advanced
2:00remaining
What is the value of 'user' after parsing this input with the model?
Given this model and input, what will be the value of the 'user' variable?
FastAPI
from pydantic import BaseModel, Field

class User(BaseModel):
    username: str = Field(min_length=3, max_length=8)
    active: bool = Field(default=True)

input_data = {"username": "bob"}
user = User(**input_data)
AUser(username='bob', active=True)
BUser(username='bob', active=False)
CValidationError due to missing 'active' field
DUser(username='bob') without 'active' attribute
Attempts:
2 left
💡 Hint
Check the default value of the 'active' field.
🧠 Conceptual
expert
2:30remaining
Which statement about FastAPI field constraints is TRUE?
Select the correct statement about using Field constraints in FastAPI models.
AField constraints like min_length and gt are enforced at runtime during request validation.
BField constraints only affect the OpenAPI schema but do not validate input data.
CField constraints can only be applied to string fields, not numbers.
DField constraints automatically convert invalid input to the nearest valid value.
Attempts:
2 left
💡 Hint
Think about when and how Pydantic validates data in FastAPI.

Practice

(1/5)
1. In FastAPI, what is the main purpose of using Field() in a Pydantic model?
easy
A. To define API routes
B. To create database tables automatically
C. To add validation rules and metadata to model fields
D. To handle HTTP requests directly

Solution

  1. Step 1: Understand the role of Pydantic models in FastAPI

    Pydantic models define the data structure and validation for request and response data.
  2. Step 2: Identify what Field() adds

    Field() allows adding constraints like min/max length, default values, and descriptions to model fields.
  3. Final Answer:

    To add validation rules and metadata to model fields -> Option C
  4. Quick Check:

    Field() = validation and metadata [OK]
Hint: Field() is for validation and extra info on model fields [OK]
Common Mistakes:
  • Thinking Field() creates routes or handles requests
  • Confusing Field() with database table creation
  • Assuming Field() is for HTTP methods
2. Which of the following is the correct way to require a string field with a minimum length of 3 in a Pydantic model using Field()?
easy
A. name: str = Field(required=True, length=3)
B. name: str = Field(min=3)
C. name: str = Field(length=3)
D. name: str = Field(min_length=3)

Solution

  1. Step 1: Recall the correct parameter for minimum length in Field()

    The correct parameter to set minimum string length is min_length.
  2. Step 2: Check each option for correct syntax

    name: str = Field(min_length=3) uses min_length=3, which is correct. Others use invalid or incorrect parameters.
  3. Final Answer:

    name: str = Field(min_length=3) -> Option D
  4. Quick Check:

    Minimum string length uses min_length [OK]
Hint: Use min_length for string length constraints in Field() [OK]
Common Mistakes:
  • Using min instead of min_length for strings
  • Using length instead of min_length
  • Adding required=True which is not a Field() parameter
3. Given this Pydantic model snippet:
from pydantic import BaseModel, Field

class Item(BaseModel):
    price: float = Field(gt=0)
    name: str = Field(min_length=2, max_length=10)

What happens if you create Item(price=-5, name='A')?
medium
A. Validation error because price is not greater than 0 and name is too short
B. Item is created successfully with given values
C. Validation error only for price, name is accepted
D. Validation error only for name, price is accepted

Solution

  1. Step 1: Check the constraints on price

    Price must be greater than 0 (gt=0). Given price is -5, which fails this.
  2. Step 2: Check the constraints on name

    Name must have length between 2 and 10. Given name is 'A' (length 1), which fails min_length=2.
  3. Final Answer:

    Validation error because price is not greater than 0 and name is too short -> Option A
  4. Quick Check:

    Both price and name fail constraints [OK]
Hint: Check all Field constraints; both price and name fail here [OK]
Common Mistakes:
  • Assuming only one field causes error
  • Ignoring min_length constraint on strings
  • Thinking negative price passes gt=0
4. What is wrong with this FastAPI Pydantic model field definition?
from pydantic import BaseModel, Field

class User(BaseModel):
    age: int = Field(min_length=18)
medium
A. Field cannot be used with integers
B. min_length is invalid for integer fields
C. Missing default value for age
D. Age should be a string, not int

Solution

  1. Step 1: Understand Field constraints for int type

    Integer fields use gt or ge for minimum value, not min_length.
  2. Step 2: Identify the error in the code

    Using min_length on an int field causes a validation error because it applies only to strings or collections.
  3. Final Answer:

    min_length is invalid for integer fields -> Option B
  4. Quick Check:

    min_length applies to strings, not ints [OK]
Hint: Use gt/ge for numbers, min_length for strings only [OK]
Common Mistakes:
  • Using string constraints on numeric fields
  • Thinking Field() can't be used with int
  • Confusing default value requirement
5. You want to create a FastAPI model for a product with a tags field that must be a list of strings, each string at least 2 characters long. Which is the best way to enforce this using Pydantic Field()?
hard
A. from typing import List from pydantic import BaseModel, Field, conlist, constr class Product(BaseModel): tags: conlist(constr(min_length=2))
B. from typing import List from pydantic import BaseModel, Field class Product(BaseModel): tags: List[str] = Field(min_length=2)
C. from typing import List from pydantic import BaseModel, Field class Product(BaseModel): tags: List[str] = Field(min_items=2)
D. from typing import List from pydantic import BaseModel, Field class Product(BaseModel): tags: List[str] = Field(min_length=2, max_length=10)

Solution

  1. Step 1: Understand the requirement for list of strings with string length constraints

    We need to enforce each string in the list to have at least 2 characters.
  2. Step 2: Identify how to apply constraints on list items

    Pydantic's constr can constrain strings, and conlist can constrain lists of constrained types.
  3. Step 3: Evaluate options

    from typing import List from pydantic import BaseModel, Field, conlist, constr class Product(BaseModel): tags: conlist(constr(min_length=2)) uses conlist(constr(min_length=2)) which correctly enforces each string's min length inside the list. Others either apply min_length to the list itself or incorrectly.
  4. Final Answer:

    Use conlist with constr to enforce string length inside list -> Option A
  5. Quick Check:

    conlist(constr(min_length=2)) = correct nested constraints [OK]
Hint: Use conlist with constr for list of strings with length limits [OK]
Common Mistakes:
  • Applying min_length to the list instead of strings inside
  • Not using constr for string constraints
  • Confusing min_items with min_length
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