Introduction
On Day 1, I created my first FastAPI application and learned how to run it locally.
Today, I focused on an important concept in API development: how to define, validate, and manage the data received by an API.
When an application receives information from a user or another application, we cannot simply assume that the data is correct. It may contain missing fields, incorrect values, or unexpected data types.
This is where Pydantic becomes useful.
1. Understanding Python Type Hints
Python is a dynamically typed language. We can assign different types of values to variables.
For example:
incident_id = 1001
severity = "CRITICAL"
Python allows us to write type hints to communicate what type of value we expect.
incident_id: int = 1001
severity: str = "CRITICAL"
Here:
-
intindicates an integer. -
strindicates a string.
My learning: Type hints improve code readability and help developers understand the expected data types. However, type hints alone do not automatically validate incoming API data at runtime.
2. What Is Pydantic?
Pydantic is a Python library used to validate and manage data based on defined models.
FastAPI uses Pydantic to validate incoming request data.
For example, imagine that an incident management application receives information about a production issue.
We may expect the following information:
- Title of the incident
- Description of the issue
- Severity
- Other required details
Instead of manually checking every field, we can define a Pydantic model.
3. Creating an IncidentCreate Model
I created an IncidentCreate model to represent the information required when a user submits a new incident.
The model defines the expected structure of the incoming data.
For example, a simplified Pydantic model looks like this:
from pydantic import BaseModel
class IncidentCreate(BaseModel):
title: str
description: str
severity: str
Now, the application has a clear definition of the expected input.
If the incoming data does not match the model requirements, Pydantic can report a validation error.
In the actual exercise, I also explored field constraints and restricting severity values to an allowed set using Literal.
4. Understanding Optional Values and Field Constraints
Not every field in an application needs to be mandatory.
Python's optional type annotations help describe values that may be absent or None.
For example:
from typing import Optional
description: Optional[str] = None
Pydantic also provides Field to define additional rules for fields, such as minimum or maximum length.
This helps us define data requirements more clearly.
My learning: Validation should happen at the application boundary. It is better to identify invalid input early than allow incorrect data to travel through the application.
5. Why Do We Need Separate Request and Response Models?
One important concept I learned today is that the data received by an API and the data returned by an API do not always have the same structure.
For example:
Request model – IncidentCreate
The user provides information such as the incident title, description, and severity.
Response model – IncidentResponse
The application can return additional information, such as:
- Generated incident ID
- Incident status
- Creation timestamp
The user does not need to provide these system-generated values.
This is why I created two separate models:
-
IncidentCreate– defines incoming data. -
IncidentResponse– defines outgoing data.
Keeping them separate makes the API structure clearer and easier to maintain.
6. Understanding model_dump()
Pydantic provides a useful method called model_dump().
It converts a Pydantic model into a Python dictionary.
Example:
incident_data = incident_input.model_dump()
Sometimes, we need to pass the dictionary values into another model.
Python's dictionary unpacking operator ** makes this convenient.
response = IncidentResponse(
**incident_input.model_dump(),
id=1001,
status="OPEN"
)
Here:
-
model_dump()converts the input model into a dictionary. -
**unpacks the dictionary values. - Additional fields are supplied when creating the response.
This is useful when building API responses from validated input data.
7. My Practical Exercise and Result
I created and tested the models in my local project.
The exercise helped me understand how to:
- Define a Pydantic model.
- Validate incoming incident information.
- Separate request and response structures.
- Convert a model into a dictionary using
model_dump(). - Create a response model using dictionary unpacking.
My test successfully created an incident response with the following example values:
ID: 1001
Severity: CRITICAL
Status: OPEN
Timestamp: UTC timestamp
This confirmed that the input data could be used to construct a response containing additional application-generated information.
8. Important Lessons from Day 2
| Concept | What I understood |
|---|---|
| Type hints | Communicate expected data types |
| Pydantic | Validates and manages structured data |
| BaseModel | Base class for creating Pydantic models |
| Field | Adds constraints to model fields |
| Optional values | Allow a field to be absent or None
|
| Literal | Restricts a field to specified values |
| Request model | Defines the data received by an API |
| Response model | Defines the data returned by an API |
| model_dump() | Converts a Pydantic model into a dictionary |
** |
Unpacks dictionary values into function or model arguments |
9. Final Thoughts
Today I understood that API development is not just about creating endpoints.
A good API should also define what data it accepts, validate that data, and return a consistent response.
Pydantic makes this process easier by allowing us to define data structures and validation rules using Python classes.
I also learned why separating request and response models is useful when developing maintainable applications.
My key takeaway from Day 2:
An API should not blindly trust incoming data. It should validate the data before using it.
What Comes Next?
In Day 3, I will continue developing the Incident Management API and work on accepting incident creation requests through an actual API endpoint.
The goal is to connect the models I created today with the FastAPI application.
Top comments (0)