Captain's Log, Stardate 29092016.5. For the past few days, we have been working on the API that will be responsible for pushing the data sent by the client into the database. It is all very simple in theory, but it is always a challenge to come up with a good, consistent flow for an application - when it is just a simple task, such as pushing data, it is all very straight forward, but when it depends on foreign keys and relations, then we start having problems. For instance, it is easy to receive some information about a user (like login, password and email), and just put in the database; but if the information is stored in multiple tables (like login, password, email, list of friends, list of messages), we need to be more careful: what if one of them fails? Which one should we do first? Ensuring the correct flow for the application, while keeping modularity, and recording and treating errors correctly suddenly becomes very hard.
![OOP versus Reality](/storage/images/blog/apidesign.png "")
We are talking about APIs, not OOP, but you got the idea
The problem is common and it is not easy to avoid it, but it gets much easier to deal with when the parts require minimal effort for using, and are powerful enough to perform operations consistently. It is tempting to make APIs that are very simple: they just put/get/delete a little piece of information, and we are done. It's easy and quick to get this job done, easy to test, easy to understand, and simplicity is good. But as a consequence, the code outside of it will pay the price: all the logic that you saved in the API may have to go somewhere else. For instance: say you need to design an API that logs items into the database. Easy, just design something like this:
It takes one item and records it. Done. The problem comes when you realize that you may receive a list of items to insert. What do you do then? You will have to make a loop that does this call over and over again - if it is an ajax request, you will have to use promises or nest several callbacks just to insert several items. It would have been much better to design an API that is capable of accepting a list of comma-separated items after all:
If you are using an SQL database, it is easy to insert items in bulk; if you are using NoSQL, just split the string and you'll have an array ready to be inserted. Simplicity is nice, it should always be present, but we also have to make sure that what we are designing fulfills the scenarios we are expecting: if you expect to receive several items, don't design something that only receives one and has to be called over and over again. People try to save time by making something very simple, but when it is way too simple, you are likely to pay the price later. It takes more time to build this base, but you will be able to code the rest of the application in a breeze.