FastAPI: Data Models
FastAPI is an incredibly flexible Python library for creating API endpoints. It is also extremely easy to learn.
Previously, we looked at the very basics of FastAPI, and I introduced an API for a bare-bones Slack clone.
Our API has just four endpoints:
- get_status: returns the system status;
- get_channels: returns a list of channels;
- post_message: stores a new message; and
- get_messages: returns a list of messages for a specified channel.
Previously, we created the status endpoint, which is just about the simplest endpoint you can create.
Let’s now go up one level in complexity and create the remaining endpoints. Here is the complete code:
Note that in a real application, our code would store all channels and messages in a database, but my example uses in-memory data structures to keep the code minimally simple.
FastAPI leverages the Pydantic library for defining data models. These data models are exposed as inputs or outputs to API endpoints.
Pydantic data models are simply classes with attributes, and these attributes are defined with types. Pydantic provides several standard data types, such as str, bool, and int, but it also includes a variety of additional types, such as FilePath and EmailStr (see Pydantic Field Types for a complete list).
In our example above, we have used Pydantic to define a Message class with just three attributes. Note in particular that our data model extends the Pydantic BaseModel, and that each of our attributes is defined as strings. This class is then passed as input to the post_message method and as output from the get_messages method.
As before, you can spin up your API like so:
uvicorn slack:app — reload
You can then go to http://localhost:8000/docs, and try out various endpoints.
First, try posting a new message to a channel and then verify that you can get the message back. You can also try out various error conditions — for example, if you post a message without an author, Pydantic will automatically validate your message and return a 422 error message with specific details.
There is a lot more to FastAPI, but you now have the basics. For more details, check out the Official FastAPI Tutorial. I also highly recommend Michael Herman’s blog post on Deploying Machine Learning models with FastAPI.