Chapter 6.  Working with Models, SQLAlchemy, and Hyperlinked APIs in Flask

In this chapter, we will expand the capabilities of the RESTful API that we started in the previous chapter. We will use SQLAlchemy as our ORM to work with a PostgreSQL database and we will take advantage of advanced features included in Flask and Flask-RESTful that will allow us to easily organize code for complex APIs, such as models and blueprints. In this chapter, we will:

  • Design a RESTful API to interact with a PostgreSQL database
  • Understand the tasks performed by each HTTP method
  • Install packages to simplify our common tasks
  • Create and configure the database
  • Write code for the models with their relationships
  • Use schemas to validate, serialize, and deserialize models
  • Combine blueprints with resourceful routing
  • Register the blueprint and run migrations
  • Create and retrieve related resources

Designing a RESTful API to interact with a PostgreSQL database

So far, our RESTful API has performed CRUD operations on a simple dictionary that acted as a data repository. Now, we want to create a more complex RESTful API with Flask RESTful to interact with a database model that has to allow us to work with messages that are grouped into message categories. In our previous RESTful API, we used a string attribute to specify the message category for a message. In this case, we want to be able to easily retrieve all the messages that belong to a specific message category, and therefore, we will have a relationship between a message and a message category.

We must be able to perform CRUD operations on different related resources and resource collections. The following list enumerates the resources and the class name that we will create to represent the model:

  • Message categories (Category model)
  • Messages (Message model)

The message category (Category) just requires an integer name, and we need the following data for a message (Message):

  • An integer identifier
  • A foreign key to a message category (Category)
  • A string message
  • The duration in seconds that will indicate the time the message has to be printed on the OLED display
  • The creation date and time. The timestamp will be added automatically when adding a new message to the collection
  • An integer counter that indicates the times the message has been printed in the OLED display
  • A bool value indicating whether the message was printed at least once on the OLED display

Tip

We will take advantage of the many packages related to Flask RESTful and SQLAlchemy that make it easier to serialize and deserialize data, perform validations, and integrate SQLAlchemy with Flask and Flask RESTful.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.12.50