DEV Community

Cover image for The Learner’s Point #01: Pydantic — Bringing TypeScript-Like Validation to Python
Prasoon Jadon for Brain Buffering

Posted on Edited on

The Learner’s Point #01: Pydantic — Bringing TypeScript-Like Validation to Python

I am not a teacher or anything. Through this series, The Learner's Point, I am not here to teach you. I am just here to share what I know and what I have been learning lately.

And in the comments, you can share what you know. We are going to learn from each other.

So, let's start exploring something new!

What is Pydantic?

If you have ever worked with TypeScript, you probably know how useful type definitions can be when working with JavaScript applications.

TypeScript provides a static type system that helps developers catch type-related errors during development. It works beautifully with ecosystems like React and Node.js.

But what about Python developers?

Well, Pydantic is one interesting answer.

You can think of Pydantic as bringing a TypeScript-like data-validation experience to Python, but with runtime validation.

And why do we need it?

In small applications, you can validate data manually. You can write conditions to check whether a particular value is an integer, string, or something else.

But what happens when you start working with larger applications, APIs, and complex data structures?

Writing validation logic for everything manually becomes repetitive and difficult to maintain.

Python dictionaries also don't provide built-in validation for their contents.

That's where Pydantic comes into action!

Installation

Installing Pydantic is pretty simple. You can use either pip or uv.

I personally sometimes use both. And honestly, pip doesn't take that much time either!

For this tutorial, let's use pip.

pip install pydantic
Enter fullscreen mode Exit fullscreen mode

I am installing it too because I don't currently have it installed in this environment.

Our First Pydantic Program

Before moving further, let's create our first program.

from pydantic import BaseModel

class Tutorial(BaseModel):
    title: str
    isPublished: bool

tutorial = Tutorial(
    title="Pydantic is TypeScript for Python",
    isPublished=True
)

print(tutorial)

print(tutorial.title)

print(tutorial.isPublished)
Enter fullscreen mode Exit fullscreen mode

Output:

title='Pydantic is TypeScript for Python' isPublished=True

Pydantic is TypeScript for Python

True
Enter fullscreen mode Exit fullscreen mode

Now, let's understand what we just wrote.

Understanding Model and BaseModel

Before understanding the code, let's understand two important things.

1. What is a Model?

A model is a class that defines the structure of data. It specifies which fields should exist and what type of data each field is expected to contain.

For example, our Tutorial model contains two fields:

  • title: It expects a string.
  • isPublished: It expects a boolean value.

2. What is BaseModel?

BaseModel is a fundamental class provided by Pydantic.

Developers inherit from this class to create their own Pydantic models.

It provides several built-in capabilities:

  • Data validation: Checks whether provided data follows the defined structure and types.
  • Type conversion: Converts compatible input values into their expected types when permitted.
  • Error handling: Raises validation errors when data doesn't meet the requirements.
  • Serialization: Converts model instances into dictionaries and JSON.
  • Field management: Organizes data according to the fields defined in the model.

In simple words, BaseModel provides the functionality, while our custom model defines the structure of the data.

Understanding Our First Program

Now let's break down our code.

1. Importing BaseModel

from pydantic import BaseModel
Enter fullscreen mode Exit fullscreen mode

First of all, we import BaseModel from the Pydantic library.

We need this because our custom model will inherit its functionality.

2. Creating Our Model

class Tutorial(BaseModel):
    title: str
    isPublished: bool
Enter fullscreen mode Exit fullscreen mode

Here, we create a class named Tutorial that inherits from BaseModel.

Notice something?

We haven't used a normal Python class alone. We have extended BaseModel to get Pydantic's functionality.

Inside the class, we define two fields:

  • title: str means title is expected to contain a string.
  • isPublished: bool means isPublished is expected to contain a boolean.

These are called type annotations.

3. Creating a Model Instance

tutorial = Tutorial(
    title="Pydantic is TypeScript for Python",
    isPublished=True
)
Enter fullscreen mode Exit fullscreen mode

Now we create an instance of our Tutorial model.

We provide values for both fields.

Pydantic checks the supplied data against the model's definitions when this instance is created.

If the data is valid, the instance is created successfully.

4. Printing the Model

print(tutorial)
Enter fullscreen mode Exit fullscreen mode

This prints the model instance along with its field names and values.

5. Accessing Individual Fields

print(tutorial.title)
print(tutorial.isPublished)
Enter fullscreen mode Exit fullscreen mode

We can also access individual fields using dot notation, just like ordinary Python objects.

That's why we get the title and publication status separately.

What Happens If We Provide Invalid Data?

Let's experiment a little.

What if we change our program to this?

tutorial = Tutorial(
    title="Pydantic is TypeScript for Python",
    isPublished="hello"
)
Enter fullscreen mode Exit fullscreen mode

Here, we are providing a string instead of a boolean.

Pydantic will raise a ValidationError because it cannot interpret "hello" as a valid boolean value.

This is one of the major advantages of using Pydantic.

It doesn't just help us define the structure of our data; it also checks the data when we create model instances.

That's All for Today!

And that's how we created our first Pydantic model using BaseModel.

We have explored what Pydantic is, why developers use it, how to install it, and how to create and use our first model.

There is still a lot more to explore, but let's not rush!

In the next part, we will explore how Pydantic handles different data types and how type conversion works.

And as always, if you know something interesting about Pydantic or have a better way to approach something discussed here, share it in the comments.

The Learner's Point #01: Getting Started with Pydantic and BaseModel

I am not a teacher or anything. Through this series, The Learner's Point, I am not here to teach you. I am just here to share what I know and what I have been learning lately.

And in the comments, you can share what you know. We are going to learn from each other.

So, let's start exploring something new!

What is Pydantic?

If you have ever worked with TypeScript, you probably know how useful type definitions can be when working with JavaScript applications.

TypeScript provides a static type system that helps developers catch type-related errors during development. It works beautifully with ecosystems like React and Node.js.

But what about Python developers?

Well, Pydantic is one interesting answer.

You can think of Pydantic as bringing a TypeScript-like data-validation experience to Python, but with runtime validation.

And why do we need it?

In small applications, you can validate data manually. You can write conditions to check whether a particular value is an integer, string, or something else.

But what happens when you start working with larger applications, APIs, and complex data structures?

Writing validation logic for everything manually becomes repetitive and difficult to maintain.

Python dictionaries also don't provide built-in validation for their contents.

That's where Pydantic comes into action!

Installation

Installing Pydantic is pretty simple. You can use either pip or uv.

I personally sometimes use both. And honestly, pip doesn't take that much time either!

For this tutorial, let's use pip.

pip install pydantic
Enter fullscreen mode Exit fullscreen mode

I am installing it too because I don't currently have it installed in this environment.

Our First Pydantic Program

Before moving further, let's create our first program.

from pydantic import BaseModel

class Tutorial(BaseModel):
    title: str
    isPublished: bool

tutorial = Tutorial(
    title="Pydantic is TypeScript for Python",
    isPublished=True
)

print(tutorial)

print(tutorial.title)

print(tutorial.isPublished)
Enter fullscreen mode Exit fullscreen mode

Output:

title='Pydantic is TypeScript for Python' isPublished=True

Pydantic is TypeScript for Python

True
Enter fullscreen mode Exit fullscreen mode

Now, let's understand what we just wrote.

Understanding Model and BaseModel

Before understanding the code, let's understand two important things.

1. What is a Model?

A model is a class that defines the structure of data. It specifies which fields should exist and what type of data each field is expected to contain.

For example, our Tutorial model contains two fields:

  • title: It expects a string.
  • isPublished: It expects a boolean value.

2. What is BaseModel?

BaseModel is a fundamental class provided by Pydantic.

Developers inherit from this class to create their own Pydantic models.

It provides several built-in capabilities:

  • Data validation: Checks whether provided data follows the defined structure and types.
  • Type conversion: Converts compatible input values into their expected types when permitted.
  • Error handling: Raises validation errors when data doesn't meet the requirements.
  • Serialization: Converts model instances into dictionaries and JSON.
  • Field management: Organizes data according to the fields defined in the model.

In simple words, BaseModel provides the functionality, while our custom model defines the structure of the data.

Understanding Our First Program

Now let's break down our code.

1. Importing BaseModel

from pydantic import BaseModel
Enter fullscreen mode Exit fullscreen mode

First of all, we import BaseModel from the Pydantic library.

We need this because our custom model will inherit its functionality.

2. Creating Our Model

class Tutorial(BaseModel):
    title: str
    isPublished: bool
Enter fullscreen mode Exit fullscreen mode

Here, we create a class named Tutorial that inherits from BaseModel.

Notice something?

We haven't used a normal Python class alone. We have extended BaseModel to get Pydantic's functionality.

Inside the class, we define two fields:

  • title: str means title is expected to contain a string.
  • isPublished: bool means isPublished is expected to contain a boolean.

These are called type annotations.

3. Creating a Model Instance

tutorial = Tutorial(
    title="Pydantic is TypeScript for Python",
    isPublished=True
)
Enter fullscreen mode Exit fullscreen mode

Now we create an instance of our Tutorial model.

We provide values for both fields.

Pydantic checks the supplied data against the model's definitions when this instance is created.

If the data is valid, the instance is created successfully.

4. Printing the Model

print(tutorial)
Enter fullscreen mode Exit fullscreen mode

This prints the model instance along with its field names and values.

5. Accessing Individual Fields

print(tutorial.title)
print(tutorial.isPublished)
Enter fullscreen mode Exit fullscreen mode

We can also access individual fields using dot notation, just like ordinary Python objects.

That's why we get the title and publication status separately.

What Happens If We Provide Invalid Data?

Let's experiment a little.

What if we change our program to this?

tutorial = Tutorial(
    title="Pydantic is TypeScript for Python",
    isPublished="hello"
)
Enter fullscreen mode Exit fullscreen mode

Here, we are providing a string instead of a boolean.

Pydantic will raise a ValidationError because it cannot interpret "hello" as a valid boolean value.

This is one of the major advantages of using Pydantic.

It doesn't just help us define the structure of our data; it also checks the data when we create model instances.

That's All for Today!

And that's how we created our first Pydantic model using BaseModel.

We have explored what Pydantic is, why developers use it, how to install it, and how to create and use our first model.

There is still a lot more to explore, but let's not rush!

In the next part, we will explore how Pydantic handles different data types and how type conversion works.

And as always, if you know something interesting about Pydantic or have a better way to approach something discussed here, share it in the comments.

Don't Know Python Yet? I've Got Something for You!

And if you don't know Python yet, don't worry! I've got something for you.

Before exploring Pydantic, you might want to get familiar with Python fundamentals. And for that, I have found some really interesting beginner-friendly tutorials.

These tutorials are written by Star (@star123) in a very friendly and creative way, using the world of Necoz and its cats to make programming concepts easier to understand.

Here are some of them:

  1. Python Loops – Necoz: The UFO Kingdom
  2. Python Variables – The Great Cat Party on Necoz Planet
  3. Python Operators – The Biggest Earthquake on Necoz
  4. Python Functions – The Function Factory of Necoz
  5. Python Data Types – Necoz School Picnic

You can also explore more tutorials on Star's Dev.to profile.

Go through these tutorials, get familiar with the basics of Python, and then come back here to explore Pydantic – our little TypeScript-like companion in the Python ecosystem!

Happy learning!

Top comments (12)

Collapse
 
robertpaschal profile image
Odinaka Robert Nnamani •

A validation error that lists every bad field at once is the detail to keep. A model that refuses bad data at the boundary saves the debugging later.

Collapse
 
pjdeveloper896 profile image
Prasoon Jadon Brain Buffering •

Yes, definitely! Proper validation at the boundary goes a long way. Providing an error message that lists all the fields having invalid data rather than validating each field one by one helps tremendously. Better early detection than having to debug the same problem again later on.

Collapse
 
robertpaschal profile image
Odinaka Robert Nnamani •

listing every invalid field in one error is the part most people skip. one round trip instead of five, and the debugging starts at the right place.

Thread Thread
 
pjdeveloper896 profile image
Prasoon Jadon Brain Buffering •

Exactly! Validation shouldn't feel like a guessing game where developers fix one error only to discover another on the next request. Returning all invalid fields together makes debugging faster and the API experience much more developer-friendly.

Thread Thread
 
robertpaschal profile image
Odinaka Robert Nnamani •

the guessing game is the part that stings. all the fields at once and the debugging starts in the right place.

Collapse
 
emilywoodsnyc profile image
Emily Woods •

For the next instalment, I’d compare a value that gets converted successfully with one that should be rejected. That turns the model’s accepted input policy into something visible, rather than assuming every type mismatch is an error. In this Python debugging prompt, I’d use the same approach for booking inputs: write down the intended rule before asking an assistant to change validation.

Collapse
 
pjdeveloper896 profile image
Prasoon Jadon Brain Buffering •

Great idea! If we compare the value that converts and the one that should not convert, we will make the model boundaries even more clear. The point to define what kind of input should be expected by the model is really good – it means that we cannot call each type error.

Collapse
 
azharabbas profile image
Azhar Abbas •

The runtime part is the real difference, since TypeScript types disappear once the code runs while Pydantic actually checks the incoming data.

Collapse
 
pjdeveloper896 profile image
Prasoon Jadon Brain Buffering •

Spot on! That is the difference. TypeScript offers compile-time type safety, but the types do not guarantee anything in the running program. Pydantic adds more to validation as it checks incoming data when the program is running. This is why runtime validation becomes so critical in handling external input.

Collapse
 
mestonecold profile image
Shruti Shahi Brain Buffering •

great first post Prasoon! ✨🐱

Collapse
 
pjdeveloper896 profile image
Prasoon Jadon Brain Buffering •

Thank you , 💫

Collapse
 
mudassirworks profile image
Mudassir Khan •

the type conversion bullet is where i would slow down for anyone coming from TypeScript. pydantic in default mode quietly turns the string 1 into an int and the string yes into true, and we shipped a bug where a stray yes flipped a feature flag because nothing complained. strict mode on boundary models fixed it. will the next part cover lax versus strict mode and what coerces silently?