To Create An Evolvable API, Stop Thinking About URLs
Tags: softwaredevelopment, javascript, api, programming
Published: 2023-05-13 05:46:48

---
title: To Create An Evolvable API, Stop Thinking About URLs
published: true
tags: softwaredevelopment,javascript,api,programming
canonical_url: https://fagnerbrack.com/to-create-an-evolvable-api-stop-thinking-about-urls-2ad8b4cc208e
---

#### The basics of API design

![](https://cdn-images-1.medium.com/max/1024/1*FwQsJ9LCwuOii7u-mYCrKw.jpeg)<figcaption>The picture of a male <a href="https://en.wikipedia.org/wiki/Peafowl">peafowl</a> standing on the grass. The bird is fanning its tail, displaying all the feathers. The feathers are enormous and contain eyespots. <a href="https://en.wikipedia.org/wiki/Peafowl#Evolution_and_sexual_selection">According to Charles Darwin</a>, the peafowl has developed this setup to attract females.</figcaption>

An evolvable API is an API that can change with the least amount of effort without [speculation or over-engineering](https://hackernoon.com/how-to-accept-over-engineering-for-what-it-really-is-6fca9a919263). It’s a way to model the communication between two computers in the form of a **conversation**. Most APIs can leverage the power of evolvability. However, as there’s no [silver bullet](https://fagnerbrack.com/how-to-reject-the-belief-on-the-silver-bullet-1d86b686acbb), a mere [Remote Procedure Call](https://en.wikipedia.org/wiki/Remote_procedure_call) may be enough for what you’re trying to achieve.

This post shows some code examples of how to store the state in the network and the fundamentals of an evolvable API. It also talks about how a uniform interface is essential to decouple client and server.

Imagine you have the website of a clinic where patients can book an appointment to a doctor. You need to develop an API so that third-party developers can integrate with the booking system of that clinic. The API should be able to change in the face of new business requirements.

For this post, let's ignore authentication and only focus on business requirements.

Nowadays, a standard solution is to create an end-point that accepts an HTTP POST request in a /booking end-point. The request takes two parameters to indicate the patient username and the intended doctor. Also, it takes another two parameters to represent the time they want to book and the contents of that booking.

Here's how the code looks like for a request to book an appointment at 10:20 in the morning:

{% gist https://gist.github.com/FagnerMartinsBrack/5cce211a3a21a83e1dc848c910b8cc78 %}

One week later, business rules change. Now the doctor "Jane" only works in 15 minutes time slots instead of 30 minutes and the working day starts at 10 AM. The time of 10:20 AM is now invalid.

Nowadays, one standard solution to handle this change is to introduce a new version to the end-point. If clients try to book an invalid date, the new version responds with a validation status code 422 Unprocessable Entity without breaking clients using the old version.

Another alternative is to create a GET /booking end-point. The response returns the time slots the doctor Jane has available so that clients can analyze and pick the ones they prefer.

Here's how the client code looks like for the second approach:

{% gist https://gist.github.com/FagnerMartinsBrack/99888db9392ae5945f0724ff82ee90af %}

![](https://cdn-images-1.medium.com/max/641/1*0wCDL1rFpt07US2oIuyAGA.png)<figcaption>A diagram that shows the client in the left and the server in the right. The client makes a GET request to the "/booking" end-point, looks at the response and then synchronously makes a POST request to the same end-point.</figcaption>

This example shows some critical aspects people get wrong with APIs:

- The client code owns the URL and the methods. The server doesn’t have control over where the client makes the next request. Therefore, the server can’t change their URLs or methods because those changes can break somebody else.
- Business changes in the server are very likely to cause breaking changes in the clients. That forces the server to create a rigid response body and implement URL versioning to remain backward compatible.
- The client needs to find out exactly which parameters the server accepts on every end-point. They need to search those parameters either through Swagger docs or code examples in the "Developer" section of the website.

The main problem here is that most of the changes in the business requirements have a higher chance to break everybody.

Instead of forcing clients to have previous knowledge of all URLs, fields, and HTTP methods, the client can ask the server what it wants, and the server can provide the information the client needs. The only code the client needs to write is the code to interpret the message.

With that in mind, let's reimagine the same booking system.

Instead of starting with the code, though, let's first understand how people book an appointment without the technology:

> \*Customer arrives at the clinic\*

> **Customer:** Hi, I want to make an appointment.

> **Receptionist:** What’s your name?

> **Customer:** Mary.

> **Receptionist:** What you want to book?

> **Customer:** I want to consult with doctor Jane.

> **Receptionist:** We have these time slots available, which one do you prefer?

> **Customer:** That one.

> \*Conversation ends\*

As a server, you can ask the clients which information they need. Exactly how you would do if you were a receptionist in real life. After you understand how people book an appointment without the technology, you'll learn **very early** some subtle rules from the business. For example, each doctor has a different set of working hours; therefore, the receptionist needs to know the intended doctor before providing the available time slots, not after.

The server doesn’t know what you want; it only knows the description of the fields, which are empty by default. The client who wants to book an appointment has the intelligence to fill those fields and provide the necessary information to the server:

{% gist https://gist.github.com/FagnerMartinsBrack/ff27e58fae538e86bf25d577cb7319b1 %}

The /start-booking is the "entry point." The "entry point" is the only URL the client needs to initiate a conversation. That makes sense because in real life you also need to know which **clinic** and **receptionist** to contact; you need to know the **host** and the **path**. The client understands when the server asks for those questions and has some logic to fill the value of each field accordingly.

In the previous example, look at the value for the fields where the read-only property is true. The client puts the fields in the request body, and the server returns them in the next response. You can develop a contract telling clients not to fill the values for the fields that have a read-only property with the value of true.

**That is how you store the state in the network.**

Neither the client or the server needs to be the permanent canonical source for the state. The state is in the conversation. You can write some code that sends the payload back to each subsequent request using a recursive strategy like this:

{% gist https://gist.github.com/FagnerMartinsBrack/e37d8961472b98702514c4f45b574fe8 %}

This way, the server can change the time slots, and the client code won't break. In the code example above, there's a function with the name "fill fields." That function represents the brain of the client, the "driver." It has the domain logic to consume the fields and select the time slots. That brain can have the intelligence to pick the best time slot available for their needs exactly how a human would do.

> An Evolvable API is a different architectural style, a way to think about how two computers communicate.

![](https://cdn-images-1.medium.com/max/1024/1*RB1cTzCpt9bPQpUrszo1KQ.png)<figcaption>A diagram that shows the machine driver on the left and the client code. The server is in the right. Each the server and the driver have their representation as a brain. The driver initiates a GET request to the server using the client code and asks for the booking; the server returns the fields so that the driver can fill them. The server eventually returns the option to book, and the driver follows that option. As a final step of the conversation, the “exit point”, the server may return the booking as successful or unsuccessful.</figcaption>

It’s possible that the machine driver is not smart enough to pick the best available time slot. After all, their brain is only composed of boards and circuits. In that case, you can use a UI so that the value for each field can come from a human after they’re presented with a list to select and text inputs to type. Instead of the machine serving as the brain to execute with intelligence, the driver is the person who’s booking: a **human brain**!

{% gist https://gist.github.com/FagnerMartinsBrack/0fef5db5d87cd875fabd7d41143ad6fb %}

In this style, the server defines actions, URLs, and methods. Also, the server defines which fields are necessary to complete the conversation and drivers can write code to look for those fields. The client always sends the state back to the server on every step of the conversation.

![](https://cdn-images-1.medium.com/max/1024/1*VRa72QNSc49APwQ2GaP5oA.png)<figcaption>A diagram that shows a human driver on the left. The client code is a CLI. The server is in the right. Each the server and the human driver have their representation as a brain. The driver initiates a GET request to the server using the CLI and asks for the booking; the server returns the fields so that the user can fill them using the interface of the command prompt. The server eventually returns the option to book, the CLI shows that as a selectable option that the user can choose. As a final step of the conversation, the server may return the booking as successful or unsuccessful, which the CLI might represent in their own way.</figcaption>

These are the critical aspects which makes an API evolvable:

- You store the **state** of the conversation in the **network**. If the server wants to track the booking transaction and the client always send the fields back, the server can create a new field with the value containing the transaction id. You don't have to change any code in the client. Everything works.
- You don’t need versioning. You can add or remove data from the response of any request and clients know how to react to it. For example, the CLI may not present an option to initiate the booking if the server returns with validation errors; the server decides if that option should be visible. If clients don’t know how to interpret a new feature from the server, say to add a mask for certain types of fields, they can ignore that feature and keep working the old way.
- The server owns the "actions" which contain the values for the URLs, methods, and fields. This way they can control where the clients go to continue the conversation. The exception is the first call, the "entry point." The "entry point" need to be hardcoded in the client. There are many ways to model this idea; you don’t need to use the term “action” as the examples of this post are using.

Here’s why having the control of URLs in the server is very important:

- The server can run A/B testing and direct clients to different servers running the same instance of the application without changes in the clients.
- The server can decide to implement a polling functionality to track the status of a booking asynchronously without changes in the clients.
- The server can change the intermediary URLs, methods or responses and there's no need to make any backward-compatible change in the clients, only forward changes.

The difference between an evolvable API approach and the RPC one is that it makes new business requirements easier to implement. It also forces you to **think** about how systems and teams communicate in your domain. The tradeoff is a small design investment.

There's no magic. If the client or the server decides to fill the user\_name with an “underscore” instead of username without an "underscore" and that field is mandatory, then obviously the server will never complete the conversation. It may error out with an API rate limit if the code enters an infinite loop. There are some things like the field names that both systems need to agree, that's the API contract.

> Start thinking about capabilities, not URLs.

If you want to design evolvable APIs, the first thing you need to understand is that URLs are a meaningless implementation detail, except for the "entry-point." If you're spending your time discussing if URLs should be in the singular /restaurant/:id or plural /restaurants/:id, then that means you're not creating evolvable APIs. Also, if you model URLs with IDs, you may inadvertently expose sensitive data that can affect the security of your application.

For every request to the same host, regardless of the URL, the client should be able to interpret the contents of that response and fill the data the server needs. The server may ask for all the fields in the first request, or they may acknowledge some fields and ask for the remaining ones in another request

The most important bit here is that the server responds to each interaction with the same **uniform** [**interface**](https://codeburst.io/why-do-you-need-to-know-interface-fundamentals-a129ac6ab0c3). This way, the code that you write for one response works for any kind of response in the same host, as long as the host sends the response in the agreed format.

This way you have no coupling between one specific URL and the response. One team can develop the client, and another team can develop the server; they only need to agree on the communication format. There's no need to deploy both client and server [at the same time in a specific order](https://fagnerbrack.com/front-end-separation-and-the-irrational-love-for-curly-braces-b6472f48bde7)!

> Every code you write should have the power to interpret any response from any URL of an API.

Imagine you're booking a doctor's appointment in real life. When you call or get to the clinic (the host), you search for the receptionist to ask for what you need to make the booking (the path for the "entry point"). The receptionist gives you a list of possible times, and you pick one (as the client). If that list doesn't show the whole day, you ask for more (pagination).

You and the clinic know what a "list of available times" or a "booking" means, that’s the **domain vocabulary**. The server’s response, which contains the "data" property as the first level document structure, comes from the [JSON API](https://jsonapi.org/format/#document-structure) specification. The JSON API spec is the **language** both systems use to communicate. Two systems can’t understand each other only with a language; they need to understand the domain vocabulary.

The current state of the conversation is in the mutual understanding of both parties. The receptionist knows you're in the process of picking a time; you know you're in the process of choosing the time you prefer. Nobody is using a sheet of paper to store the state of the conversation; both parties know the state. The state is in the network, not in a database.

> To have an efficient conversation, having a generic language is not enough. When you design an API, it’s your job as a programmer to develop the domain vocabulary.

In Domain Driven Design, you model the architecture of the code with how the people from your business operate. With an evolvable API, it's the same. You model the asynchronous communication between machines exactly how people in your business communicate.

Think about how people would solve the business problem without technology and use technology to enhance the business.

If you write the code to interpret the message of the server and the server provides an evolvable API, you'll see that over time you'll be able to fit many business requirements with the minimal amount of effort. That means fewer code changes and less breakage for the code you don't control.

Now here's the catch: this is not a new idea.

Most of the developers who design APIs these days are struggling with problems that somebody else have already figured out more than 15 years ago. Given this post is becoming considerably big, I won’t tell you where this idea comes from and who is that “somebody else.” That's a subject for another post.

For now, I can only say it’s time for you and me to get some rest.

Thanks for reading. If you have some feedback, reach out to me on [Twitter](https://twitter.com/FagnerBrack), [Facebook](https://www.facebook.com/fagner.brack) or [Github](http://github.com/FagnerMartinsBrack).

Thanks to **Danil Suits** , **Sebastian Arrue** , [Mike Amundsen](https://twitter.com/mamund), [Wael Emara](https://twitter.com/wael_emara), and [Guilherme Tramontina](https://twitter.com/gtramontina) for their insightful inputs to this post.