March 09, 2020

Creating a middleware API with Python

The advantage of Python is, that it can be used for many things. It's used for creating GUI prototypes, testing out new algorithm, as a replacement for bash scripts or to program games. Python can even be used for creating the business logic in a database application and this should be described in the following blogpost.

The business logic is sometimes called a middleware API because it connects the frontend with the SQL backend. It can be visualized with a class diagram in the UML notation. The classes are realized with SQL tables which are connected to an Entity relationship diagram.

An UML class diagram explains very well what middleware is about. It provides a high level API to the outside world and it realizes the technical details with methods and an underlying database. The good news is, that Python has built in object oriented features. It can be used for creating classes and then the classes are filled with data.

An example is available online under the term “Northwind database”. Northwind is the example database introduced by the MS-Access software which contains the table for a fictional company. From the perspective of a relational database the ER-diagram is important but from the perspective of a middleware API the items are equal to classes.

Explaining what a middleware is can be realized by give the details of how a backend and how a frontend works. A backend is equal to a SQL database for example the sqlite software. SQLite communicates with the outside world with SQL statements. On the other hand a frontend for a database contains of a form generator which is able to draw windows on the screen. The user is allowed to press on buttons and gets the information he needs. Between the frontend and the backend there is a gap. That means, it's not possible to convert the output of the sqlite software direct into graphical information. This inbetween layer is the UML class diagram which describes the business logic from an abstract perspective.

According to Stackoverflow the simplest form of storing a python object into a file is the pickle module, https://stackoverflow.com/questions/4529815/saving-an-object-data-persistence But the pickle module will create a binary file which can't be used in external applications. The more elaborated form of storing python objects to a file is to convert it into the json format:

import json
class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age
  def getjson(self):
    return {
      'name': self.name, 
      'age': self.age,
    }
    
p=Person("peter",30)
print(p.getjson())