Before we dive into Pydantic, let's briefly introduce FastAPI. FastAPI is a modern Python web framework that simplifies the process of creating APIs. Its rapid adoption within the Python community is attributed to its exceptional performance and developer-friendly features. With FastAPI, developers can build APIs with ease, and its seamless compatibility with Pydantic adds another layer of functionality for data validation and parsing. In this article, we will delve into the world of FastAPI-Pydantic, exploring the powerful synergy between these two technologies.
Role of Pydantic in FastAPI
Pydantic is a Python library that is commonly used with FastAPI. It plays a crucial role in FastAPI applications by providing data validation, parsing, and serialization capabilities. Specifically, Pydantic is used in FastAPI. Pydantic is a Python library that shines when it comes to data validation and parsing. In FastAPI, Pydantic plays a crucial role in several key areas:
Validation Data with Pydantic
Pydantic enables developers to define data models, also known as user-defined schemas. These models can include data types, validation rules, and default values. By establishing these models, developers can ensure that incoming data adheres to the expected structure and types. This validation process guarantees the reliability and integrity of the data used in your API.
Example: Basic Data Validation
Let's say you want to validate user input for a blog post. You can define a Pydantic model to ensure the data is in the expected format. In this example, we define a BlogPost
model with fields for the title and content. Pydantic automatically validates that title
and content
are strings.
Python3
from pydantic import BaseModel, ValidationError
class BlogPost(BaseModel):
title: str
content: str
try:
# Valid data
post_data = BlogPost(title="Introduction to Pydantic",
content="Pydantic is a Python library for data validation.")
print(post_data)
# Corrected invalid data
invalid_post_data = BlogPost(title="123", content="42")
print(invalid_post_data)
except ValidationError as e:
print("Validation error:", e)
Output
title='Introduction to Pydantic' content='Pydantic is a Python library for data validation.'
title='123' content='42'
Parsing data with Pydantic
In addition to data validation, Pydantic is adept at automatically converting and parsing data from various formats, such as JSON or form data, into Python objects. These conversions are based on the previously defined models or user-defined schemas. This feature not only simplifies the data handling process but also ensures that the data is accurately transformed into a format suitable for further processing within your API.
Example: Data Parsing and Default Values
In this example, we define a User
model with default values for the 'age' field. If 'age' is not provided, it defaults to 25. You can also override the default value by providing a value during data creation.
Python3
from pydantic import BaseModel
class User(BaseModel):
username: str
email: str
age: int = 25 # Default value
# Valid data
user_data = User(username="john_doe", email="[email protected]")
print(user_data.age) # Output: 25 (default value)
# Valid data with age specified
user_data2 = User(username="jane_doe", email="[email protected]", age=30)
print(user_data2.age) # Output: 30
# Invalid data
invalid_user_data = User(username="jim_doe", email=123)
# This will raise a ValidationError for 'email' since it should be a string.
Output
25 30
Example
In this example, we are following the use case we previously discussed with Pydantic. We define a Pydantic model called 'TodoItem' to outline the data structure for Todo tasks, encompassing fields for 'title,' 'description,' and an optional 'completed' field, which defaults to 'False.' We establish an in-memory database, 'todo_db,' represented as a Python list, to store Todo items. The code encompasses two API endpoints:
- A POST endpoint at '/todos/' is designed to handle incoming requests for creating new Todo items. It expects data in the 'TodoItem' model format, appends this data to the 'todo_db' list, and responds with the newly created Todo item.
- A GET endpoint at '/todos/' retrieves a list of all existing Todo items from 'todo_db' and returns it as a response in the form of a list of 'TodoItem' objects.
In simple terms, this is a Todo task API that facilitates the creation and retrieval of Todo items. The Pydantic model ensures that the data adheres to the specified structure, and FastAPI streamlines the route creation for managing incoming requests and generating responses.
Python3
# Import required modules
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List
# Create a FastAPI app instance
app = FastAPI()
# Define a Pydantic model for Todo items
class TodoItem(BaseModel):
title: str
description: str
completed: bool = False
# Initialize an in-memory database (list) to store Todo items
todo_db = []
# Endpoint to create a new Todo item
@app.post("/todos/", response_model=TodoItem)
def create_todo(todo: TodoItem):
todo_db.append(todo) # Add the new Todo item to the database
return todo # Return the created Todo item as a response
# Endpoint to retrieve all Todo items
@app.get("/todos/", response_model=List[TodoItem])
def read_todos():
return todo_db # Return the list of all Todo items
# Add the code to run the FastAPI app directly using uvicorn
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)
Output
Output
Similar Reads
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read