0
0
FastAPIframework~5 mins

List and set validation in FastAPI

Choose your learning style9 modes available
Introduction

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.

When you expect a user to send multiple items like tags or IDs.
When you want to make sure a list has unique items using a set.
When you want to check that each item in a list or set follows certain rules.
When you want to automatically convert input data into Python lists or sets.
When you want to reject bad data early before processing it.
Syntax
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.

Examples
This model accepts a list of strings called tags. Duplicates are allowed.
FastAPI
from pydantic import BaseModel
from typing import List

class ModelWithList(BaseModel):
    tags: List[str]
This model accepts a set of integers. Duplicates will be removed automatically.
FastAPI
from pydantic import BaseModel
from typing import Set

class ModelWithSet(BaseModel):
    unique_numbers: Set[int]
This model allows the list to be empty by default.
FastAPI
from pydantic import BaseModel
from typing import List

class EmptyListModel(BaseModel):
    items: List[str] = []
This model accepts a set of unique integers.
FastAPI
from pydantic import BaseModel
from typing import Set

class SingleItemSetModel(BaseModel):
    ids: Set[int]
Sample Program

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.

FastAPI
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())
OutputSuccess
Important Notes

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.

Summary

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.