Bird
Raised Fist0
FastAPIframework~20 mins

Response model exclude and include in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Response Model Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output when using response_model_exclude in FastAPI?
Consider this FastAPI endpoint using a Pydantic model with response_model_exclude to hide some fields. What will the JSON response include?
FastAPI
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class User(BaseModel):
    id: int
    username: str
    email: str

@app.get("/user", response_model=User, response_model_exclude={"email"})
def get_user():
    return User(id=1, username="alice", email="alice@example.com")
A{"id": 1, "username": "alice"}
B{"id": 1, "username": "alice", "email": "alice@example.com"}
C{"username": "alice", "email": "alice@example.com"}
D{"id": 1, "email": "alice@example.com"}
Attempts:
2 left
💡 Hint
Think about which fields are excluded from the response model.
❓ component_behavior
intermediate
2:00remaining
How does response_model_include affect the FastAPI response?
Given this FastAPI endpoint, what fields will appear in the JSON response when using response_model_include?
FastAPI
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Product(BaseModel):
    id: int
    name: str
    price: float
    description: str

@app.get("/product", response_model=Product, response_model_include={"id", "name"})
def get_product():
    return Product(id=10, name="Book", price=12.99, description="A nice book")
A{"id": 10, "price": 12.99, "description": "A nice book"}
B{"id": 10, "name": "Book"}
C{"id": 10, "name": "Book", "price": 12.99}
D{"name": "Book", "price": 12.99, "description": "A nice book"}
Attempts:
2 left
💡 Hint
Only the fields listed in response_model_include will be shown.
📝 Syntax
advanced
2:00remaining
What error occurs with incorrect response_model_exclude syntax?
Which option shows the error raised by this FastAPI endpoint with wrong response_model_exclude syntax?
FastAPI
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    id: int
    name: str
    price: float

@app.get("/item", response_model=Item, response_model_exclude=["price"])
def get_item():
    return Item(id=5, name="Pen", price=1.5)
ANo error, runs correctly
BSyntaxError: invalid syntax
CTypeError: unhashable type: 'list'
DValueError: field 'price' not found
Attempts:
2 left
💡 Hint
Check the type expected for response_model_exclude.
❓ state_output
advanced
2:00remaining
What is the output when combining response_model_include and response_model_exclude?
Given this FastAPI endpoint, what fields will appear in the JSON response?
FastAPI
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Profile(BaseModel):
    id: int
    username: str
    email: str
    bio: str

@app.get(
    "/profile",
    response_model=Profile,
    response_model_include={"id", "username", "email"},
    response_model_exclude={"email"}
)
def get_profile():
    return Profile(id=2, username="bob", email="bob@example.com", bio="Hello!")
A{"id": 2, "username": "bob", "email": "bob@example.com"}
B{"id": 2, "username": "bob", "bio": "Hello!"}
C{"username": "bob", "email": "bob@example.com", "bio": "Hello!"}
D{"id": 2, "username": "bob"}
Attempts:
2 left
💡 Hint
Remember that response_model_exclude removes fields even if included.
🔧 Debug
expert
3:00remaining
Why does this FastAPI endpoint return all fields despite response_model_exclude?
Analyze this code. Why does the response include all fields even though response_model_exclude is set?
FastAPI
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Data(BaseModel):
    a: int
    b: int
    c: int

@app.get("/data", response_model=Data, response_model_exclude={"b"})
def get_data():
    return {"a": 1, "b": 2, "c": 3}
AThe response includes all fields because the returned value is a dict, not a Pydantic model instance.
BThe response includes all fields because <code>response_model_exclude</code> only works with lists, not sets.
CThe response includes all fields because <code>response_model_exclude</code> is ignored when returning dicts.
DThe response includes all fields because the endpoint is missing a <code>return</code> statement.
Attempts:
2 left
💡 Hint
Think about how FastAPI processes the returned data with response models.

Practice

(1/5)
1. What does the response_model_exclude parameter do in FastAPI?
easy
A. It includes only specified fields in the API response.
B. It hides specified fields from the API response.
C. It changes the data type of response fields.
D. It validates the response data against the model.

Solution

  1. Step 1: Understand the purpose of response_model_exclude

    This parameter is used to remove or hide certain fields from the response data.
  2. Step 2: Compare with other parameters

    Unlike response_model_include which shows only specified fields, response_model_exclude hides specified fields.
  3. Final Answer:

    It hides specified fields from the API response. -> Option B
  4. Quick Check:

    Exclude means hide fields [OK]
Hint: Exclude hides fields; include shows fields [OK]
Common Mistakes:
  • Confusing exclude with include
  • Thinking it changes data types
  • Assuming it validates data
2. Which of the following is the correct way to exclude the field password from a FastAPI response model?
easy
A. response_model_include=['password']
B. response_model_include={'password'}
C. response_model_exclude={'password'}
D. response_model_exclude=['password']

Solution

  1. Step 1: Identify correct data type for exclude

    The response_model_exclude parameter expects a set or dict of field names to exclude.
  2. Step 2: Check syntax correctness

    Using a set like {'password'} is valid; lists are not accepted and cause ValueError.
  3. Final Answer:

    response_model_exclude={'password'} -> Option C
  4. Quick Check:

    Exclude uses set or dict of fields [OK]
Hint: Use set {'password'} to exclude fields [OK]
Common Mistakes:
  • Using include instead of exclude
  • Using a list ['password'] instead of set {'password'}
  • Passing a string instead of set
3. Given this FastAPI endpoint:
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class User(BaseModel):
    id: int
    username: str
    email: str
    password: str

@app.get('/user', response_model=User, response_model_exclude={'password'})
def get_user():
    return User(id=1, username='alice', email='alice@example.com', password='secret')
What will the API response JSON include?
medium
A. {"id": 1, "username": "alice", "email": "alice@example.com"}
B. {"id": 1, "username": "alice", "email": "alice@example.com", "password": "secret"}
C. {"username": "alice", "email": "alice@example.com"}
D. {"id": 1, "password": "secret"}

Solution

  1. Step 1: Understand response_model_exclude effect

    The password field is excluded from the response, so it will not appear in the JSON output.
  2. Step 2: Identify included fields

    All other fields id, username, and email remain and appear in the response.
  3. Final Answer:

    {"id": 1, "username": "alice", "email": "alice@example.com"} -> Option A
  4. Quick Check:

    Excluded field missing in output [OK]
Hint: Excluded fields do not appear in response JSON [OK]
Common Mistakes:
  • Expecting excluded fields to appear
  • Confusing exclude with include
  • Ignoring response_model parameter
4. You wrote this FastAPI endpoint:
@app.get('/item', response_model=Item, response_model_include=['name', 'price'])
def get_item():
    return Item(id=5, name='Book', price=10.0, description='A good read')
But the endpoint raises a ValueError instead of returning the filtered response. What is the likely error?
medium
A. Using a list instead of a set for response_model_include
B. The response_model_include parameter should be a set, not a list
C. The response_model_include parameter is ignored if not a set or dict
D. The response_model_include parameter must be a dictionary

Solution

  1. Step 1: Check expected type for response_model_include

    FastAPI expects response_model_include to be a set or dict of fields, not a list.
  2. Step 2: Understand why list fails

    Passing a list causes a ValueError because Pydantic requires set or dict for include/exclude.
  3. Final Answer:

    Using a list instead of a set for response_model_include -> Option A
  4. Quick Check:

    Include needs set or dict [OK]
Hint: Use set {} for include, not list [] [OK]
Common Mistakes:
  • Using list instead of set for include
  • Expecting include to filter with wrong type
  • Not checking parameter types
5. You want to return a user response with only id and username fields included, but exclude password and email. Which is the best way to do this in FastAPI?
hard
A. Use response_model_exclude={'password', 'email'} to exclude unwanted fields.
B. Return a custom dictionary with only id and username instead of the model.
C. Use both response_model_include={'id', 'username'} and response_model_exclude={'password', 'email'} together.
D. Use response_model_include={'id', 'username'} to include only needed fields.

Solution

  1. Step 1: Understand include vs exclude

    Including only id and username is simpler and clearer than excluding fields.
  2. Step 2: Avoid mixing include and exclude

    Using both can cause confusion or unexpected results; better to use include to specify exactly what to show.
  3. Final Answer:

    Use response_model_include={'id', 'username'} to include only needed fields. -> Option D
  4. Quick Check:

    Include specifies exact fields to show [OK]
Hint: Use include to specify exact fields to show [OK]
Common Mistakes:
  • Mixing include and exclude causing conflicts
  • Excluding fields but missing some unwanted fields
  • Returning raw dict instead of model
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