Body - Nested Models

Warning

The current page still doesn’t have a translation for this language.

But you can help translating it: Contributing.

With FastAPI, you can define, validate, document, and use arbitrarily deeply nested models (thanks to Pydantic).

List fields

You can define an attribute to be a subtype. For example, a Python list:

  1. from typing import Optional
  2. from fastapi import FastAPI
  3. from pydantic import BaseModel
  4. app = FastAPI()
  5. class Item(BaseModel):
  6. name: str
  7. description: Optional[str] = None
  8. price: float
  9. tax: Optional[float] = None
  10. tags: list = []
  11. @app.put("/items/{item_id}")
  12. async def update_item(item_id: int, item: Item):
  13. results = {"item_id": item_id, "item": item}
  14. return results

This will make tags be a list of items. Although it doesn’t declare the type of each of the items.

List fields with type parameter

But Python has a specific way to declare lists with internal types, or “type parameters”:

Import typing’s List

First, import List from standard Python’s typing module:

  1. from typing import List, Optional
  2. from fastapi import FastAPI
  3. from pydantic import BaseModel
  4. app = FastAPI()
  5. class Item(BaseModel):
  6. name: str
  7. description: Optional[str] = None
  8. price: float
  9. tax: Optional[float] = None
  10. tags: List[str] = []
  11. @app.put("/items/{item_id}")
  12. async def update_item(item_id: int, item: Item):
  13. results = {"item_id": item_id, "item": item}
  14. return results

Declare a List with a type parameter

To declare types that have type parameters (internal types), like list, dict, tuple:

  • Import them from the typing module
  • Pass the internal type(s) as “type parameters” using square brackets: [ and ]
  1. from typing import List
  2. my_list: List[str]

That’s all standard Python syntax for type declarations.

Use that same standard syntax for model attributes with internal types.

So, in our example, we can make tags be specifically a “list of strings”:

  1. from typing import List, Optional
  2. from fastapi import FastAPI
  3. from pydantic import BaseModel
  4. app = FastAPI()
  5. class Item(BaseModel):
  6. name: str
  7. description: Optional[str] = None
  8. price: float
  9. tax: Optional[float] = None
  10. tags: List[str] = []
  11. @app.put("/items/{item_id}")
  12. async def update_item(item_id: int, item: Item):
  13. results = {"item_id": item_id, "item": item}
  14. return results

Set types

But then we think about it, and realize that tags shouldn’t repeat, they would probably be unique strings.

And Python has a special data type for sets of unique items, the set.

Then we can import Set and declare tags as a set of str:

  1. from typing import Optional, Set
  2. from fastapi import FastAPI
  3. from pydantic import BaseModel
  4. app = FastAPI()
  5. class Item(BaseModel):
  6. name: str
  7. description: Optional[str] = None
  8. price: float
  9. tax: Optional[float] = None
  10. tags: Set[str] = set()
  11. @app.put("/items/{item_id}")
  12. async def update_item(item_id: int, item: Item):
  13. results = {"item_id": item_id, "item": item}
  14. return results

With this, even if you receive a request with duplicate data, it will be converted to a set of unique items.

And whenever you output that data, even if the source had duplicates, it will be output as a set of unique items.

And it will be annotated / documented accordingly too.

Nested Models

Each attribute of a Pydantic model has a type.

But that type can itself be another Pydantic model.

So, you can declare deeply nested JSON “objects” with specific attribute names, types and validations.

All that, arbitrarily nested.

Define a submodel

For example, we can define an Image model:

  1. from typing import Optional, Set
  2. from fastapi import FastAPI
  3. from pydantic import BaseModel
  4. app = FastAPI()
  5. class Image(BaseModel):
  6. url: str
  7. name: str
  8. class Item(BaseModel):
  9. name: str
  10. description: Optional[str] = None
  11. price: float
  12. tax: Optional[float] = None
  13. tags: Set[str] = []
  14. image: Optional[Image] = None
  15. @app.put("/items/{item_id}")
  16. async def update_item(item_id: int, item: Item):
  17. results = {"item_id": item_id, "item": item}
  18. return results

Use the submodel as a type

And then we can use it as the type of an attribute:

  1. from typing import Optional, Set
  2. from fastapi import FastAPI
  3. from pydantic import BaseModel
  4. app = FastAPI()
  5. class Image(BaseModel):
  6. url: str
  7. name: str
  8. class Item(BaseModel):
  9. name: str
  10. description: Optional[str] = None
  11. price: float
  12. tax: Optional[float] = None
  13. tags: Set[str] = []
  14. image: Optional[Image] = None
  15. @app.put("/items/{item_id}")
  16. async def update_item(item_id: int, item: Item):
  17. results = {"item_id": item_id, "item": item}
  18. return results

This would mean that FastAPI would expect a body similar to:

  1. {
  2. "name": "Foo",
  3. "description": "The pretender",
  4. "price": 42.0,
  5. "tax": 3.2,
  6. "tags": ["rock", "metal", "bar"],
  7. "image": {
  8. "url": "http://example.com/baz.jpg",
  9. "name": "The Foo live"
  10. }
  11. }

Again, doing just that declaration, with FastAPI you get:

  • Editor support (completion, etc), even for nested models
  • Data conversion
  • Data validation
  • Automatic documentation

Special types and validation

Apart from normal singular types like str, int, float, etc. You can use more complex singular types that inherit from str.

To see all the options you have, checkout the docs for Pydantic’s exotic types. You will see some examples in the next chapter.

For example, as in the Image model we have a url field, we can declare it to be instead of a str, a Pydantic’s HttpUrl:

  1. from typing import Optional, Set
  2. from fastapi import FastAPI
  3. from pydantic import BaseModel, HttpUrl
  4. app = FastAPI()
  5. class Image(BaseModel):
  6. url: HttpUrl
  7. name: str
  8. class Item(BaseModel):
  9. name: str
  10. description: Optional[str] = None
  11. price: float
  12. tax: Optional[float] = None
  13. tags: Set[str] = []
  14. image: Optional[Image] = None
  15. @app.put("/items/{item_id}")
  16. async def update_item(item_id: int, item: Item):
  17. results = {"item_id": item_id, "item": item}
  18. return results

The string will be checked to be a valid URL, and documented in JSON Schema / OpenAPI as such.

Attributes with lists of submodels

You can also use Pydantic models as subtypes of list, set, etc:

  1. from typing import List, Optional, Set
  2. from fastapi import FastAPI
  3. from pydantic import BaseModel, HttpUrl
  4. app = FastAPI()
  5. class Image(BaseModel):
  6. url: HttpUrl
  7. name: str
  8. class Item(BaseModel):
  9. name: str
  10. description: Optional[str] = None
  11. price: float
  12. tax: Optional[float] = None
  13. tags: Set[str] = []
  14. images: Optional[List[Image]] = None
  15. @app.put("/items/{item_id}")
  16. async def update_item(item_id: int, item: Item):
  17. results = {"item_id": item_id, "item": item}
  18. return results

This will expect (convert, validate, document, etc) a JSON body like:

  1. {
  2. "name": "Foo",
  3. "description": "The pretender",
  4. "price": 42.0,
  5. "tax": 3.2,
  6. "tags": [
  7. "rock",
  8. "metal",
  9. "bar"
  10. ],
  11. "images": [
  12. {
  13. "url": "http://example.com/baz.jpg",
  14. "name": "The Foo live"
  15. },
  16. {
  17. "url": "http://example.com/dave.jpg",
  18. "name": "The Baz"
  19. }
  20. ]
  21. }

Info

Notice how the images key now has a list of image objects.

Deeply nested models

You can define arbitrarily deeply nested models:

  1. from typing import List, Optional, Set
  2. from fastapi import FastAPI
  3. from pydantic import BaseModel, HttpUrl
  4. app = FastAPI()
  5. class Image(BaseModel):
  6. url: HttpUrl
  7. name: str
  8. class Item(BaseModel):
  9. name: str
  10. description: Optional[str] = None
  11. price: float
  12. tax: Optional[float] = None
  13. tags: Set[str] = []
  14. images: Optional[List[Image]] = None
  15. class Offer(BaseModel):
  16. name: str
  17. description: Optional[str] = None
  18. price: float
  19. items: List[Item]
  20. @app.post("/offers/")
  21. async def create_offer(offer: Offer):
  22. return offer

Info

Notice how Offer has a list of Items, which in turn have an optional list of Images

Bodies of pure lists

If the top level value of the JSON body you expect is a JSON array (a Python list), you can declare the type in the parameter of the function, the same as in Pydantic models:

  1. images: List[Image]

as in:

  1. from typing import List
  2. from fastapi import FastAPI
  3. from pydantic import BaseModel, HttpUrl
  4. app = FastAPI()
  5. class Image(BaseModel):
  6. url: HttpUrl
  7. name: str
  8. @app.post("/images/multiple/")
  9. async def create_multiple_images(images: List[Image]):
  10. return images

Editor support everywhere

And you get editor support everywhere.

Even for items inside of lists:

Body - Nested Models - 图1

You couldn’t get this kind of editor support if you where working directly with dict instead of Pydantic models.

But you don’t have to worry about them either, incoming dicts are converted automatically and your output is converted automatically to JSON too.

Bodies of arbitrary dicts

You can also declare a body as a dict with keys of some type and values of other type.

Without having to know beforehand what are the valid field/attribute names (as would be the case with Pydantic models).

This would be useful if you want to receive keys that you don’t already know.


Other useful case is when you want to have keys of other type, e.g. int.

That’s what we are going to see here.

In this case, you would accept any dict as long as it has int keys with float values:

  1. from typing import Dict
  2. from fastapi import FastAPI
  3. app = FastAPI()
  4. @app.post("/index-weights/")
  5. async def create_index_weights(weights: Dict[int, float]):
  6. return weights

Tip

Have in mind that JSON only supports str as keys.

But Pydantic has automatic data conversion.

This means that, even though your API clients can only send strings as keys, as long as those strings contain pure integers, Pydantic will convert them and validate them.

And the dict you receive as weights will actually have int keys and float values.

Recap

With FastAPI you have the maximum flexibility provided by Pydantic models, while keeping your code simple, short and elegant.

But with all the benefits:

  • Editor support (completion everywhere!)
  • Data conversion (a.k.a. parsing / serialization)
  • Data validation
  • Schema documentation
  • Automatic docs