Skip to content
Advertisement

Pydantic schema logic

So, I’m building an API to interact with my personal wine labels collections database. For what I understand, a pydantic model purpose is to serve as a “verifier” of the schema that is sent to the API. So, my pydantic schema for adding a label is the following:

from pydantic import BaseModel
from typing import Optional

class WineLabels(BaseModel):
    name: Optional[str]
    type: Optional[str]
    year = Optional[int]
    grapes = Optional[str]
    country = Optional[str]
    region = Optional[str]
    price = Optional[float]
    id = Optional[str]

None of the fields is to be updated automatically. This is equal to the sqlalchemy model since I want to add all the fields manually.

So my question is, let’s say I want to create a call to search by ID and another one to search by name. I do not believe these schema should be applied. Should I create another schema ? Should I create one like this?:

class SearchWineLabel(WineLabels):
      id: str

Should a schema be created for each purpose that cannot be fulfilled by an already existing schema?

Sorry, but I can’t understand the logic behind it. Thanks!!

Advertisement

Answer

If you want to search by id or name, I’m not sure if you even need a schema – one or more get parameters would usually be enough in those cases (and is usually better semantically).

In any case, the schema would be written for what the endpoint is expected to receive, not by using a general schema that contains the field in some other way. Think of the schemas as the input/output definitions for given resources and endpoints.

You usually want to have different schemas for adding and updating (since adding will require certain fields to be present, while updating may allow null or a missing field in any location).

The Pydantic schemas will allow you to express these differences without writing code, and it will be reflected in your generated api docs under /docs

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement