Bird
Raised Fist0
FastAPIframework~8 mins

List and set validation in FastAPI - Performance & Optimization

Choose your learning style10 modes available
Performance: List and set validation
MEDIUM IMPACT
This affects server response time and payload size during API request validation.
Validating user input containing multiple items in a list or set
FastAPI
from fastapi import FastAPI
from pydantic import BaseModel
from typing import Set

app = FastAPI()

class ItemModel(BaseModel):
    tags: Set[str]

@app.post('/items/')
async def create_item(item: ItemModel):
    return {'unique_tags_count': len(item.tags)}
Using a set enforces uniqueness and reduces redundant validation, improving CPU efficiency for large inputs.
📈 Performance GainValidation time reduced by skipping duplicates; memory usage optimized by storing unique items only.
Validating user input containing multiple items in a list or set
FastAPI
from fastapi import FastAPI
from pydantic import BaseModel
from typing import List

app = FastAPI()

class ItemModel(BaseModel):
    tags: List[str]

@app.post('/items/')
async def create_item(item: ItemModel):
    return {'tags_count': len(item.tags)}
Using a generic list without constraints causes slower validation and larger memory use for big inputs.
📉 Performance CostValidation time grows linearly with list size; no deduplication causes redundant processing.
Performance Comparison
PatternValidation CPU CostMemory UsageResponse DelayVerdict
List without type or constraintsHigh (linear with size)High (stores duplicates)Higher delay with large input[X] Bad
Typed Set with uniqueness enforcedMedium (skips duplicates)Lower (unique items only)Lower delay[OK] Good
Rendering Pipeline
In FastAPI, list and set validation happens during request parsing before response generation. Large or complex collections increase CPU load and delay response serialization.
→Request Parsing
→Validation
→Response Serialization
⚠️ BottleneckValidation stage is most expensive when processing large collections due to type checks and uniqueness enforcement.
Optimization Tips
1Use typed sets to enforce uniqueness and reduce redundant validation.
2Limit input size with constraints to avoid excessive CPU and memory use.
3Avoid generic untyped lists for large inputs to improve validation speed.
Performance Quiz - 3 Questions
Test your performance knowledge
What is a performance benefit of using a set instead of a list for input validation in FastAPI?
AIt slows down validation because sets are unordered.
BIt increases the size of the payload sent over the network.
CIt automatically removes duplicate items, reducing validation work.
DIt requires more memory to store duplicates.
DevTools: Network and Performance panels
How to check: Use Network panel to inspect request and response sizes; use Performance panel to record and analyze server response time during validation.
What to look for: Look for long server processing times and large payload sizes indicating inefficient validation or large input data.

Practice

(1/5)
1. In FastAPI, when should you use List instead of Set for request data validation?
easy
A. When you want to store only unique items without order
B. When you want to automatically remove duplicates
C. When you want to validate a single item only
D. When the order of items matters and duplicates are allowed

Solution

  1. Step 1: Understand List characteristics

    A List keeps the order of items and allows duplicates.
  2. Step 2: Compare with Set characteristics

    A Set removes duplicates and does not guarantee order.
  3. Final Answer:

    When the order of items matters and duplicates are allowed -> Option D
  4. Quick Check:

    List = ordered with duplicates [OK]
Hint: Use List for ordered duplicates, Set for unique unordered [OK]
Common Mistakes:
  • Confusing Set with List and expecting order
  • Using Set when duplicates are needed
  • Thinking List removes duplicates automatically
2. Which of the following is the correct way to declare a FastAPI endpoint expecting a set of integers in the request body?
easy
A. def endpoint(items: List[int]):
B. def endpoint(items: Set[int]):
C. def endpoint(items: dict[int]):
D. def endpoint(items: tuple[int]):

Solution

  1. Step 1: Identify the correct type for unique collection

    Set[int] is used to declare a set of integers with unique values.
  2. Step 2: Verify other options

    List[int] allows duplicates, dict[int] is invalid syntax, tuple[int] is fixed-length and ordered.
  3. Final Answer:

    def endpoint(items: Set[int]): -> Option B
  4. Quick Check:

    Set[int] = unique integer collection [OK]
Hint: Use Set[int] for unique integer collections in FastAPI [OK]
Common Mistakes:
  • Using dict[int] which is invalid syntax
  • Using tuple[int] which expects fixed length
  • Confusing List with Set for uniqueness
3. Given this FastAPI endpoint code snippet, what will be the output if the input JSON is {"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)}
medium
A. {"unique_items": [1, 2, 3]}
B. {"unique_items": [1, 2, 2, 3]}
C. ValidationError due to duplicate items
D. {"unique_items": []}

Solution

  1. Step 1: Understand Set validation in Pydantic

    Pydantic converts the input list to a set, removing duplicates automatically.
  2. Step 2: Analyze the input and output

    Input has duplicates [1, 2, 2, 3], output converts to unique set [1, 2, 3].
  3. Final Answer:

    {"unique_items": [1, 2, 3]} -> Option A
  4. Quick Check:

    Set removes duplicates automatically [OK]
Hint: Set input removes duplicates, output shows unique items [OK]
Common Mistakes:
  • Expecting ValidationError on duplicates
  • Assuming output keeps duplicates
  • Confusing List and Set behavior
4. Identify the error in this FastAPI model using List and Set:
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)
medium
A. No error, code works fine
B. Using List instead of Set for unique_ids is correct
C. Assigning a set to a List field breaks Pydantic validation
D. Missing type annotation for unique_ids

Solution

  1. Step 1: Check field type and assignment

    unique_ids is declared as List[int] but assigned a set in __init__, causing type mismatch.
  2. Step 2: Understand Pydantic validation rules

    Pydantic expects unique_ids to be a list; assigning a set breaks validation and type consistency.
  3. Final Answer:

    Assigning a set to a List field breaks Pydantic validation -> Option C
  4. Quick Check:

    Field type must match assigned value [OK]
Hint: Match field type with assigned value to avoid validation errors [OK]
Common Mistakes:
  • Assigning set to List field without changing type
  • Ignoring Pydantic's type enforcement
  • Assuming __init__ can override field types safely
5. You want to create a FastAPI endpoint that accepts a list of tags but ensures no empty or duplicate tags. Which is the best way to validate this using Pydantic?
hard
A. Use tags: Set[str] and add a validator to reject empty strings
B. Use tags: List[str] and manually check duplicates and empties in the endpoint
C. Use tags: List[str] with a validator that converts to set and removes empties
D. Use tags: Set[str] without any validator

Solution

  1. Step 1: Ensure uniqueness with Set

    Using Set[str] automatically removes duplicates.
  2. Step 2: Add validator to reject empty strings

    Since Set only ensures uniqueness, a validator is needed to reject empty tags.
  3. Final Answer:

    Use tags: Set[str] and add a validator to reject empty strings -> Option A
  4. Quick Check:

    Set + validator = unique + no empty tags [OK]
Hint: Use Set for uniqueness and validator for empties [OK]
Common Mistakes:
  • Using List without uniqueness enforcement
  • Not validating empty strings in Set
  • Relying on manual checks in endpoint instead of validators
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