Sunday, December 22, 2024

How to use Pedantic to declare JSON data models (Data shapes)

 First, you need to import BaseModel from pydantic and then use it to create subclasses defining the schema, or data shapes, you want to receive.

Next, you declare your data model as a class that inherits from BaseModel, using standard Python types for all the attributes:

# main.py

from typing import Optional

from fastapi import FastAPI

from pydantic import BaseModel


class Item(BaseModel):

    name: str

    description: Optional[str] = None

    price: float

    tax: Optional[float] = None


app = FastAPI()


@app.post("/items/")

async def create_item(item: Item):

    return item


When a model attribute has a default value, it is not required. Otherwise, it is required. To make an attribute optional, you can use None.


For example, the model above declares a JSON object (or Python dict) like this:


{

    "name": "Foo",

    "description": None,

    "price": 45.2,

    "tax": None

}


In this case, since description and tax are optional because they have a default value of None, this JSON object would also be valid:


{

    "name": "Foo",

    "price": 45.2

}


A JSON object that omits the default values is also valid.

Next, add the new pydantic model to your path operation as a parameter. You declare it the same way you declared path parameters:



# main.py


from typing import Optional


from fastapi import FastAPI

from pydantic import BaseModel


class Item(BaseModel):

    name: str

    description: Optional[str] = None

    price: float

    tax: Optional[float] = None


app = FastAPI()


@app.post("/items/")

async def create_item(item: Item):

    return item

The parameter item has a type hint of Item, which means that item is declared as an instance of the class Item.

With that Python type declaration, FastAPI will:

Read the body of the request as JSON

Convert the corresponding types if needed

Validate the data and return a clear error if it is invalid

Give you the received data in the parameter item—since you declared it to be of type Item, you will also have all the editor support, with completion and type checks for all the attributes and their types

By using standard type hints with pydantic, FastAPI helps you build APIs that have all these best practices by default, with little effort.


References:

https://realpython.com/fastapi-python-web-apis/#create-a-first-api


No comments:

Post a Comment