We use list and set validation to make sure the data we get is the right kind and shape. This helps keep our app safe and working well.
List and set validation in FastAPI
from pydantic import BaseModel from typing import List, Set class MyModel(BaseModel): names: List[str] # List of strings unique_ids: Set[int] # Set of unique integers
Use List when order matters and duplicates are allowed.
Use Set when you want only unique items and order does not matter.
from pydantic import BaseModel from typing import List class ModelWithList(BaseModel): tags: List[str]
from pydantic import BaseModel from typing import Set class ModelWithSet(BaseModel): unique_numbers: Set[int]
from pydantic import BaseModel from typing import List class EmptyListModel(BaseModel): items: List[str] = []
from pydantic import BaseModel from typing import Set class SingleItemSetModel(BaseModel): ids: Set[int]
This FastAPI app defines a POST endpoint that accepts a JSON body with a list of names and a set of unique IDs. The set automatically removes duplicates. The test client sends data with duplicates to show how validation works.
from fastapi import FastAPI from pydantic import BaseModel from typing import List, Set from fastapi.testclient import TestClient app = FastAPI() class ItemModel(BaseModel): names: List[str] unique_ids: Set[int] @app.post('/items/') async def create_item(item: ItemModel): return { 'names_received': item.names, 'unique_ids_received': sorted(item.unique_ids) } client = TestClient(app) # Test data with duplicates in list and set response = client.post('/items/', json={ 'names': ['apple', 'banana', 'apple'], 'unique_ids': [1, 2, 2, 3] }) print('Status code:', response.status_code) print('Response JSON:', response.json())
List validation keeps the order and allows duplicates.
Set validation removes duplicates automatically but does not keep order.
Validation happens automatically when FastAPI receives data matching the model.
Use sorted() if you want to display set items in order.
Use List for ordered collections that can have duplicates.
Use Set for collections that must have unique items.
FastAPI with Pydantic validates and converts input data automatically.
Practice
List instead of Set for request data validation?Solution
Step 1: Understand List characteristics
A List keeps the order of items and allows duplicates.Step 2: Compare with Set characteristics
A Set removes duplicates and does not guarantee order.Final Answer:
When the order of items matters and duplicates are allowed -> Option DQuick Check:
List = ordered with duplicates [OK]
- Confusing Set with List and expecting order
- Using Set when duplicates are needed
- Thinking List removes duplicates automatically
Solution
Step 1: Identify the correct type for unique collection
Set[int] is used to declare a set of integers with unique values.Step 2: Verify other options
List[int] allows duplicates, dict[int] is invalid syntax, tuple[int] is fixed-length and ordered.Final Answer:
def endpoint(items: Set[int]): -> Option BQuick Check:
Set[int] = unique integer collection [OK]
- Using dict[int] which is invalid syntax
- Using tuple[int] which expects fixed length
- Confusing List with Set for uniqueness
{"items": [1, 2, 2, 3]}?
from fastapi import FastAPI
from pydantic import BaseModel
from typing import Set
app = FastAPI()
class Data(BaseModel):
items: Set[int]
@app.post("/unique")
def unique_items(data: Data):
return {"unique_items": list(data.items)}Solution
Step 1: Understand Set validation in Pydantic
Pydantic converts the input list to a set, removing duplicates automatically.Step 2: Analyze the input and output
Input has duplicates [1, 2, 2, 3], output converts to unique set [1, 2, 3].Final Answer:
{"unique_items": [1, 2, 3]} -> Option AQuick Check:
Set removes duplicates automatically [OK]
- Expecting ValidationError on duplicates
- Assuming output keeps duplicates
- Confusing List and Set behavior
from pydantic import BaseModel
from typing import List, Set
class Model(BaseModel):
names: List[str]
unique_ids: List[int]
def __init__(self, **data):
super().__init__(**data)
self.unique_ids = set(self.unique_ids)Solution
Step 1: Check field type and assignment
unique_ids is declared as List[int] but assigned a set in __init__, causing type mismatch.Step 2: Understand Pydantic validation rules
Pydantic expects unique_ids to be a list; assigning a set breaks validation and type consistency.Final Answer:
Assigning a set to a List field breaks Pydantic validation -> Option CQuick Check:
Field type must match assigned value [OK]
- Assigning set to List field without changing type
- Ignoring Pydantic's type enforcement
- Assuming __init__ can override field types safely
Solution
Step 1: Ensure uniqueness with Set
Using Set[str] automatically removes duplicates.Step 2: Add validator to reject empty strings
Since Set only ensures uniqueness, a validator is needed to reject empty tags.Final Answer:
Use tags: Set[str] and add a validator to reject empty strings -> Option AQuick Check:
Set + validator = unique + no empty tags [OK]
- Using List without uniqueness enforcement
- Not validating empty strings in Set
- Relying on manual checks in endpoint instead of validators
Ready to prove it?
Pass the test and this pattern moves unknown
