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.