CodexBloom - Programming Q&A Platform

How to implement guide with fastapi and pydantic validation for nested data models in python 3.11

πŸ‘€ Views: 70 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-11
fastapi pydantic validation Python

I've been working on this all day and I'm working with an scenario while using FastAPI with Pydantic for data validation... I have a nested data model that includes a list of items, but I'm getting a validation behavior when the input data has the wrong structure. Here’s the relevant model definition: ```python from pydantic import BaseModel, conlist class Item(BaseModel): name: str quantity: int class Order(BaseModel): items: conlist(Item, min_items=1) ``` When I try to send a request with the following payload: ```json { "items": [ { "name": "apple", "quantity": 2 }, { "name": "banana" } ] } ``` I receive the following validation behavior: ``` ValidationError: 1 validation behavior for Order items -> 1 field required (type=value_error.missing) ``` It seems like Pydantic is expecting both the `name` and `quantity` fields for every item in the list, but I only provided `name` for the second item. I thought that Pydantic would just skip over missing fields if they were optional, but it seems that's not the case here. I tried changing the `quantity` field to `Optional[int]`, but that leads to a different behavior. What's the best way to handle optional fields in a nested model like this in FastAPI with Pydantic? Am I missing something in my model definition? Any advice would be greatly appreciated. I'm working on a web app that needs to handle this. The project is a desktop app built with Python. Thanks for any help you can provide!