Pydantic Schemas for FastAPI

Git Commit: add schemas for validating usercreate
Remember the request-response cycle in the previous post? Ok, let's revise, A schema is used to validate the data we receive as well as to reformat the data that we want to send to the client/browser. Suppose, we want to receive a JSON like {'username':'testuser','email':'[email protected]','password':'testing'} but there is no way we can trust our users. Our users may send anything they want and we don't want to store it without verifying. e.g. {'username':'testuser','email':'1234','password':'testing'} Notice here email is 1234, in such cases, we want to notify our users that we can't store such 💩! For this, we can go the hard way but we have Pydantic for our rescue. We create pydantic classes that verify the types, called Schemas. Let's jump into it and see it in action. Before that let's create files and folders to hold schemas.

backend/
├─.env
├─alembic/
├─core/
│ └─config.py
├─db/
│ ├─base.py
│ ├─base_class.py
│ ├─models/          
│ │ ├─blog.py        
│ │ └─user.py 
│ └─session.py
├─alembic.ini
├─main.py
├─requirements.txt
├─schemas/          #new
  ├─blog.py         #new
  └─user.py        #new

Now, it's time to create the pydantic classes i.e. schemas. Let's start with users' schemas. Type in the following code in schemas > user.py

from pydantic import BaseModel,EmailStr, Field


#properties required during user creation
class UserCreate(BaseModel):
    email : EmailStr
    password : str = Field(..., min_length=4)

Let's understand this dark magic! We are inheriting BaseModel from pydantic. It empowers fastapi to suggest validation errors to users. In this case, whenever we want to create a user, we will receive data in JSON format where the email will be verified in proper mail format and the password will be validated to be a string with at least 4 characters length.

Because we are trying to use EmailStr from pydantic we need to install this service first. Let's add pydantic[email] to our requirements.txt file and install all requirements by pip install -r requirements.txt.

#previous requirements
alembic==1.11.1

pydantic[email] 

Schemas will be clearer when we use schemas in our routes and you see their impact in action.

FastAPITutorial

Brige the gap between Tutorial hell and Industry. We want to bring in the culture of Clean Code, Test Driven Development.

We know, we might make it hard for you but definitely worth the efforts.

Contacts

Refunds:

Refund Policy
Social

Follow us on our social media channels to stay updated.

© Copyright 2022-23 Team FastAPITutorial