Michael Adsit Technologies, LLC.

Search terms of three or more characters

Do Not Base Your APIs on Legacy

This post is meant to clarify reasons why basing your APIs upon a pre-existing system and ingrained culture can become problematic for those creating and consuming them as well as to propose some ways to help overcome that.

Working with a Legacy

Nearly every organization has some form of legacy code that has survived over time, and those working there have become used to certain patterns from seeing them for so many years. As such, the natural instinct when designing something for others to consume is to keep on using the same practices.

For instance, if one has been using a SOAP interface for internal applications for many years, the temptation when creating a REST API may be to simply take the existing SOAP WSDL and use that as the design document for the new REST API.

While this is certainly a way to start building something new, as a lot of time and effort has gone into it in the past, there are a few questions that must be asked before doing so.

  • Is my new API simply to fill a current buzz, or to create a better experience for everyone?
  • How easy is it for someone from the outside to navigate the existing documentation?
  • Does my old structure reveal information that I want to keep internal only?
  • Are there any bottlenecks to overcome in order to entice people to use my new API?
  • When exposing a way into my company from the outside world, am I keeping a secure mindset?
  • What were some issues that the newest people on the team had when learning our current design?
  • If I have a client requesting this API, what are their needs when compared to my desires?

In the past, I have experienced things such as unique identifiers being requested to be sent at the time of object creation because that was how it had been done in the original system due to the fact that the only consumer was written in a specific language and there was a centralized class distributed to create and attach this information. When dealing with a browser or other form of decentralized input it is important to consider the new situation - sometimes things that seem to be company common sense are not so.

If the documentation exists as to how the current product backend came about, that can be very useful to compare requirements for the new API versus the original backend.

Simple Legacy Example

Quick Clarification

While I have seen things similar to the given example, it is designed simply to be somewhat plausible though not very well designed. Though it is possible to use the code given, I would not recommend it. Remember that it is always important to promote team unity, and discuss things in a manner where everyone feels safe to share and work together towards a better overall product. Do not attack people's character - attack the problem together.

Actual Example

One day, a developer at the company was asked to create a standard task or todo list for their team. They make use of the company's main MySQL database, create a table, and link it to a simple database editor user interface.

1CREATE TABLE Task(
2  Task_ID INT PRIMARY KEY AUTO_INCREMENT,
3  Task TEXT,
4  Complete BOOL
5) ENGINE=INNODB;
6

At some time, another team wants to keep track of people's first and last names and creates the following table.

1CREATE TABLE Person(
2  Person_ID INT PRIMARY KEY AUTO_INCREMENT,
3  First_Name TEXT,
4  Last_Name TEXT
5) ENGINE=INNODB;
6

Down the line, someone else started using these tables - but linked them together.

1CREATE TABLE People_Assigned_Task(
2  Person_ID INT,
3  Task_ID INT,
4  FOREIGN KEY (Person_ID)
5	  REFERENCES Person(Person_ID)
6    ON DELETE CASCADE,
7	FOREIGN KEY (Task_ID)
8		REFERENCES Task(Task_ID)
9    ON DELETE CASCADE
10) ENGINE=INNODB
11

Inside the company, through hallway discussions, it became obvious how to use them. People started writing programs to link other people to tasks. Some teams started using it to report and it was informally assumed that null values in the database meant that the task was not complete. No one thought to unify the Person and People terms in the table names.

Eventually, a subset of the data looked like this.

Task Table
Task_IDTaskComplete
1My First Tasknull
2My Second Task0
3My Third Task1
4My First Task1
5My Second Task1
6My Third Task1
7My Fourth Tasknull
Person Table
Person_IDFirst_NameLast_Name
1BobJones
2LarryJones
3MoeJones
4MoeSmith

And reports were being run against it with statements such as the following to figure out who had been assigned tasks.

1SELECT 
2Person.First_Name,
3Person.Last_Name 
4FROM People_Assigned_Task
5INNER JOIN Person
6ON People_Assigned_Task.Person_ID = Person.Person_ID
7INNER JOIN Task
8ON People_Assigned_Task.Task_ID = Task.Task_ID
9
First_NameLast_Name
BobJones
MoeJones
MoeJones

This team was just curious about who had been assigned tasks, but another team was curious about who had incomplete tasks left.

1SELECT 
2Person.First_Name,
3Person.Last_Name 
4FROM People_Assigned_Task
5INNER JOIN Person
6ON People_Assigned_Task.Person_ID = Person.Person_ID
7INNER JOIN Task
8ON People_Assigned_Task.Task_ID = Task.Task_ID
9WHERE Task.Complete = false
10
First_NameLast_Name
BobJones

And over time reports with different combinations of criteria came about, some business users wanted to be able to add and review more data. Tables just kept getting added until someone came up with the brilliant idea of some arbitrary data types. Every team then started adding their own types, and would simply filter to what is needed on their team.

1CREATE TABLE Arbitrary_Data_Type(
2	Arbitrary_Data_Type_ID VARCHAR(32) NOT NULL PRIMARY KEY,
3  Extended_Description TEXT
4) ENGINE INNODB;
5
6CREATE TABLE Task_Arbitrary_Data(
7	Task_ID INT,
8  Arbitrary_Data_Type_ID VARCHAR(32),
9  `Data` TEXT,
10  PRIMARY KEY (Task_ID, Arbitrary_Data_Type_ID),
11  FOREIGN KEY (Task_ID)
12    REFERENCES Task(Task_ID)
13    ON DELETE CASCADE,
14	FOREIGN KEY (Arbitrary_Data_Type_ID)
15		REFERENCES Arbitrary_Data_Type(Arbitrary_Data_Type_ID)
16    ON DELETE CASCADE
17) ENGINE INNODB;
18

For the internal applications, this has worked out fine so far, every newcomer learns how their team makes use of it and no one really thinks too hard before adding new types. Now the time has come to make this task list available for others to use.

Transitioning from Internal Legacy to Exposed API.

Using the simple example above a client has requested the ability to see tasks themselves about the product you are working on for them. This is able to be either a REST API or JavaScript for them, they just need the definitions to mock and start building out their own user interface. Working with the security team, you come up with a solution to filter tasks and users to just what a logged in external user is able to see, so that is not a concern. You do research, and see that a collection of entities when returned should have the same data as the one specifically retrieved, and start to give the specification for the returned objects as JSON Schema so that the client can start planning for the future.

Describing the person is easy enough, as you were given guidance to give each object a generic id field instead of the specific one in the database and use snake_case for the properties. Also, it is assumed that the $id will be at a resolvable URL for validators later.

1{
2    "$schema": "http://json-schema.org/draft-07/schema",
3    "$id": "http://example.com/schemas/person.json",
4    "type": "object",
5    "title": "Person Schema",
6    "description": "The root schema for a person.",
7    "default": {},
8    "additionalProperties": false,
9    "examples": [
10        {
11            "id": 1,
12            "first_name": "Bob",
13            "last_name": "Jones"
14        }
15    ],
16    "required": [
17        "id",
18        "first_name",
19        "last_name"
20    ],
21    "properties": {
22        "id": {
23            "$id": "#/properties/id",
24            "type": "integer",
25            "title": "ID",
26            "description": "The ID for this person",
27            "default": 0,
28            "examples": [
29                1
30            ]
31        },
32        "first_name": {
33            "$id": "#/properties/first_name",
34            "type": "string",
35            "title": "First Name",
36            "description": "This is the person's given first name.",
37            "default": "",
38            "examples": [
39                "Bob",
40                "Jill"
41            ]
42        },
43        "last_name": {
44            "$id": "#/properties/last_name",
45            "type": "string",
46            "title": "Last Name",
47            "description": "This is the person's given last name.",
48            "default": "",
49            "examples": [
50                "Jones",
51                "Smith"
52            ]
53        }
54    }
55}
56

And now you move onto the task as the next base part.

1{
2    "$schema": "http://json-schema.org/draft-07/schema",
3    "$id": "http://example.com/schemas/task.json",
4    "type": "object",
5    "title": "Task Schema",
6    "description": "The root schema for a task.",
7    "default": {},
8    "additionalProperties": false,
9    "examples": [
10        {
11            "id": 1,
12            "task": "My First Task",
13            "complete": false
14        }
15    ],
16    "required": [
17        "id",
18        "task",
19        "complete"
20    ],
21    "properties": {
22        "id": {
23            "$id": "#/properties/id",
24            "type": "integer",
25            "title": "ID",
26            "description": "The ID for this task",
27            "default": 0,
28            "examples": [
29                1
30            ]
31        },
32        "task": {
33            "$id": "#/properties/task",
34            "type": "string",
35            "title": "Task",
36            "description": "What must be done for this task to be considered complete, or a summary thereof.",
37            "default": "",
38            "examples": [
39                "My First Task",
40                "Read the employee handbook"
41            ]
42        },
43        "complete": {
44            "$id": "#/properties/complete",
45            "type": "boolean",
46            "title": "Complete",
47            "description": "Has this task been completed.",
48            "default": false,
49            "examples": [
50                false,
51                true
52            ]
53        }
54    }
55}
56

Feeling happy, you are about to hand over this list when re-reading the requirements, you realize that you must be able to identify who is assigned to which task, as well as what arbitrary data is associated with this task. To help define this, you decide to use a reverse engineering tool such as the one included in MySQL Workbench in order to get an idea of what the relationships should be visually before making the JSON.

Database Diagram

Upon quickly looking, you realize that this has a relationship that could cause infinite recursion in the JSON, as tasks could belong to a person, or people could belong to a task. In addition, you start looking through the Arbitrary_Data_Type_ID values, and see things such as Length, Lgth, Time Taken, Time to Completion, Time To Completion B, all of which have an Extended_Description of The time it took to complete this task.

After taking a moment to bang your head against the wall compose yourself, it has become obvious that you could simply complete the requirement as quickly as possible to look good on the metrics and let the outside world just deal with the huge amount of types and looping through them all of the time, or you could have some meetings to discuss things internally before meeting with the client.

Before doing anything else though, you decide that it is possible to do something to avoid the infinite recursion and so decide to focus on that first.

1{
2    "$schema": "http://json-schema.org/draft-07/schema",
3    "$id": "http://example.com/schemas/task-with-people.json",
4    "type": "object",
5    "title": "Task Schema with people",
6    "description": "The root schema for a task that has people.",
7    "all-of": ["http://example.com/schemas/task.json"],
8    "default": {},
9    "examples": [
10        {
11            "id": 1,
12            "task": "My First Task",
13            "complete": false,
14            "people": [{
15              "id": 1,
16              "first_name": "Bob",
17              "last_name": "Jones"
18            }]
19        }
20    ],
21    "required": [
22        "people"
23    ],
24    "properties": {
25        "people": {
26            "$id": "#/properties/people",
27            "type": "array",
28            "title": "People",
29            "description": "The people associated with this task",
30            "default": [],
31            "examples": [{
32              "id": 1,
33              "first_name": "Bob",
34              "last_name": "Jones"
35            }],
36            "items": { "$ref": "http://example.com/schemas/person.json" }
37        }
38    }
39}
40
1{
2    "$schema": "http://json-schema.org/draft-07/schema",
3    "$id": "http://example.com/schemas/person-with-tasks.json",
4    "all-of": ["http://example.com/schemas/person.json"],
5    "type": "object",
6    "title": "Person Schema with Tasks",
7    "description": "The root schema for a person with tasks.",
8    "default": {},
9    "examples": [
10        {
11            "id": 1,
12            "first_name": "Bob",
13            "last_name": "Jones",
14            "tasks": [{
15              "id": 1,
16              "task": "My First Task",
17              "complete": false,
18            }]
19        }
20    ],
21    "required": [
22        "tasks"
23    ],
24    "properties": {
25        "tasks": {
26            "$id": "#/properties/tasks",
27            "type": "array",
28            "title": "Tasks",
29            "description": "The tasks for this person",
30            "default": [],
31            "items": { "$ref": "http://example.com/schemas/task.json" },
32            "examples": [{
33              "id": 1,
34              "task": "My First Task",
35              "complete": false,
36            }]
37        }
38    }
39}
40

Having figured out a way to avoid your API having infinite recursions as an attack vector, you have decided that the talk about references is really needed. Meetings happen internally, and you realize that you are the only one who has worked with and researched any external APIs for a long time. Those in the meetings want to have the API consumers make a separate call for each piece of arbitrary data, thinking that that will be the easiest approach without needing to be too concerned about too much data or the security of it - something like the following.

1// get with pure javascript API - ignoring async concerns
2const company_api = new CompanyAPI(MY_API_KEY)
3const tasks = company_api.tasks_with_people()
4tasks.forEach(({id})=>{
5  company_api.tasks(id).arbitrary_data('FIELD_1')
6  company_api.tasks(id).arbitrary_data('FIELD_2')
7})
8
9// or fetch (lazy template below below)
10fetch(`http://my-API/tasks/${task}/data/${arbitrary_data_id}`)
11

From your own experience, you know with certainty that you would rather have a way to get all of the required data in one swoop and plead to be able to. Something more like the below.

1// get with pure javascript API - ignoring async concerns
2const company_api = new CompanyAPI(MY_API_KEY)
3const tasks = company_api.tasks_with_people({extras: ['FIELD_1', 'FIELD_2']})
4
5// or fetch
6fetch(`http://my-API/tasks/?extras=FIELD_1&extras=FIELD2`)
7

And so, you talk about that and are told that that goes against the standards that someone else in the company came up with - they don't want to use a query string for what data is received because each element should come complete as per the definition, and in the internal system that has been how it always has been done. It is explained to you that each team has always made queries specific to how they are going to use it, and we do not allow an arbitrary amount of things to be given to each customer.

This is not the battle that you thought you were going to be fighting,~~ and so you finally just give up and give in, figuring that it is not your problem.~~ and so you request some time to see if there is a solution that respects the company tradition and that will also allow less work for those who are consuming the data. This is because you realize that the way this data is currently used does not necessarily work well outside of the teams using it. Even if it is limited to only what a customer is allowed to see, the data is not unified for them nor is it easy to give a full specification as it could change per customer.

After some thought, you propose a configurable set of defaults that can be seen by all external users, as well as customer-specific defaults for those that request them. In addition, you recommend one more part to the API to be able to retrieve what the extra keys mean. The higher-ups accept the proposed solution, and you are finally able to send some schemas over. The only difference in the base task schema is the "additionalProperties": false line changed to "additionalProperties": { "type": "string" }. However, you have forced several behind the scenes changes with the following tables.

1CREATE TABLE Arbitrary_Data_External_Defaults(
2	Arbitrary_Data_Type_ID VARCHAR(32) NOT NULL PRIMARY KEY,
3    FOREIGN KEY (Arbitrary_Data_Type_ID)
4		REFERENCES Arbitrary_Data_Type(Arbitrary_Data_Type_ID)
5        ON DELETE CASCADE
6) ENGINE INNODB;
7
8CREATE TABLE Arbitrary_Data_External_Customer_Defaults(
9	Arbitrary_Data_Type_ID VARCHAR(32) NOT NULL,
10    Customer_Name TEXT,
11    FOREIGN KEY (Arbitrary_Data_Type_ID)
12		REFERENCES Arbitrary_Data_Type(Arbitrary_Data_Type_ID)
13        ON DELETE CASCADE
14) ENGINE INNODB;
15

And the API now has one additional feature added, so you must send over one more schema.

1{
2    "$schema": "http://json-schema.org/draft-07/schema",
3    "$id": "http://example.com/schemas/task-extras.json",
4    "type": "object",
5    "title": "Task Extras Schema",
6    "description": "The root schema for describing extra fields on a task.",
7    "default": {},
8    "additionalProperties": false,
9    "examples": [
10        {
11            "property": "Time To Completion",
12            "description": "The time it took to complete this task."
13        }
14    ],
15    "required": [
16        "property",
17        "description"
18    ],
19    "properties": {
20        "property": {
21            "$id": "#/properties/property",
22            "type": "string",
23            "title": "Property",
24            "description": "A property attached to a task",
25            "default": "",
26            "examples": [
27                "Time To Completion",
28                "Why This Task?"
29            ]
30        },
31        "description": {
32            "$id": "#/properties/description",
33            "type": "description",
34            "title": "Description",
35            "description": "Why does this property exist, or what does it represent.",
36            "default": "",
37            "examples": [
38                "The time it took to complete this task.",
39                "Sometimes people just want to know why we made the task"
40            ]
41        }
42    }
43}
44

Finally, the first draft of the API is ready to send to a client. They can create a simulated person with tasks to start testing their items with, using the examples. A while later it is time for the live tests to begin and the customer gets back the data you expected.

1{
2  "id": 1,
3  "first_name": "Bob",
4  "last_name": "Jones",
5  "tasks": [{
6    "id": 1,
7    "task": "My First Task",
8    "Time To Completion": "",
9    "Why This Task?": "Just to check out the system",
10    "Extra Field": "Why do this?",
11    "complete": false
12  }]
13}
14

However, it seems that more communication needed to be done, as the client was not expecting the Extra Field property that was there. It did not do any harm but was a good reminder to communicate changes to their defaults as part of your deployment pipeline.

Conclusion

Legacy Systems come about after several years and can be hard for those who designed or have been using them for a while to question them as their experience has been that they work. Challenging the pre-existing structure can be important when creating an implementation on top of something that already exists, but doing so in a manner that listens to the concerns of others is important if you are to change perceptions in a positive manner. Some cultures are much more open to change than others, and one should work towards recognizing what is a fact and what is an opinion. So - take some time to analyze the problem with a fresh perspective, and make sure to include the team and if possible the end-user to try to come up with the best solution possible.

Tags: Best Practices, APIs, Legacy, Teamwork

©Michael Adsit Technologies, LLC. 2012-2024