Schema Validation with Pydantic

Why do we need schema?

  • It's a pain to get all the values from the body

  • The client can send whatever data they want

  • The data isn't getting validated

  • We ultimately want to force the client to send data in a schema that we expect

Pydantic

  • This is already installed if you have used the [all] installation flag

pip install fastapi[all]
  • It is it's own separate module and has nothing to do with FastAPI (can be used separately)

  • FastAPI uses it so that it can define a schema

So how do you validate the data using Pydantic?

  • First you import the BaseModel from pydantic

from pydantic import BaseModel
  • Then you define a class that inherits from the BaseModel and set up the schema

Note: In our case we just want the Title and Content to create a post

Logically these should be stings to we will set them as such

  • Once you have defined the class correctly, you can pass this to the function for the Path Operation

  • We are referencing the Post class and assigning it to a variable on line 2

  • After which we are printing the post to the console

  • The good thing about doing things in this way is that our data gets validated automatically and our API does not accept integers for example

  • It only accepts strings as input, otherwise it throws an error

If you check the console you can see the following output with the data validated:

Extracting the data:

  • This is made easy by defining the schema as mentioned above

  • All you have to do is add the field you want it to print

Output:

Data validation:

What happens if we remove the title field?

  • If we remove the title from the HTTP Packet in postman and have it as such:

  • Once you send the packet you will get the following error message:

  • It is throwing an error as it is expecting both a title and content to process

  • It let's us know that the value is missing: "type": "value_error.missing"

What happens if we provide a string as input for title?

  • We are sending the HTTP Packet via Postman as such:

  • It will not throw an error as it will try to convert whatever data we are trying to give it to the type specified (string)

Letting the user define data

  • We will have to extend our class with to look as follows:

  • Now you have 3 options on sending the HTTP Packet via Postman

Setting an optional field that defaults to None

  • You will need to import Optional from the typing library

  • Then we will extend the class for post ratings

  • Now we can send HTTP Packets like so:

  • The error raised is that the value provided is not integer: "type": "type_error.integer"

Last updated