From the course: Build REST APIs with FastAPI
Unlock this course with a free trial
Join today to access over 24,200 courses taught by industry experts.
Request body - Python Tutorial
From the course: Build REST APIs with FastAPI
Request body
The most common case in REST APIs is to pass some data as a JSON request. What FastAPI is doing is using a library called Pydantic, which is a library for validation of JSON and other things as well. So let's have a look. So here is my server. And this is server for accepting sales. So we have a post for new sale and you can also get details of a specific sale. So we're doing the usual imports from FastAPI and from Pydantic, we import base model and also a field. And now we define the model for the body of the HTTP request. So we say it's a class sale. It inherits from base model. Time is datetime. Customer_id is a string and we say it equals a field. And then we can give constraints. So Pydantic will do the check for us. And we say the customer_id must be at least two characters long. Same for SKU, the Stock Keeping Unit, or the unique identifier for that item that is being sold. How many items are sold, and the price. Both of these must be bigger than zero. And now when we get a new…