11 : Creating Schemas in Fastapi


Remember the request-response cycle in the previous post? Ok, let's revise, A schema is used to validate 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':'testuser@nofoobar.com','password':'testing'} but there is no way we ca 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 shit ! For this, we can go the hard way but we have Pydantic for our rescue. We create pydantic classes that verify the types and these classes are called Schemas. Let's jump into it and see it in action. Before that let's create files and folders to hold schemas.

│ └─general_pages/
│   └─route_homepage.py
│ └─config.py
│ ├─base.py
│ ├─base_class.py
│ ├─models/
│ │ ├─jobs.py
│ │ └─users.py
│ └─session.py
├─schemas/          #new
│ ├─jobs.py         #new
│ └─users.py        #new
│ └─images/
│   └─logo.png
  │ └─navbar.html
  │ └─homepage.html

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 > users.py

from typing import Optional
from pydantic import BaseModel,EmailStr

#properties required during user creation
class UserCreate(BaseModel):
    username: str
    email : EmailStr
    password : str

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 username will be verified to be a string, the email will be verified to be in proper mail format and the password will be validated to be a string.

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 here ...
# ....
# .... 

#for loading environment variables

#for email validation            #new

Schemas will be clearer when we will use schemas in our routes.

Prev: 10 : Creating … Next: 12 : Understanding …

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.



Refund Policy

Follow us on our social media channels to stay updated.

© Copyright 2022-23 Team FastAPITutorial