3 Tips on API Responses for Backend Developers
Tags: api, backenddevelopment, programming, softwaredevelopment
Published: 2024-01-19 21:17:43

I have been a full-stack web developer for 4 years now, but I still remember the struggle of my early days. Although I do not consider frontend development easy, I have always thought of backend development as the most tricky part of my job.

It has been a while since I coded my first API, and I have learned a lot since then. Specifically, there are 3 things I wish I had known about how to produce the perfect API response before becoming a backend developer. Now, it is time to share them, so that any backend developer reading this can benefit from them.

Let's now delve into these 3 tips on API responses.

## Always Return an Object

When building an API returning a single value, you may be tempted to serialize it directly, as follows:

```json
["Maria", "John", "Laura"]
```

This is actually a valid JSON response, as it would be:

- A string (e.g., `"Hello world"`)

- A number (e.g., `1`)

- A boolean (e.g., `true`)

- `null`

You may want to do this to keep your API response clean and simple, but it is actually a bad approach. Let me explain why.

Let's say you need to make that API return more than one value. This is a fairly common scenario. After all, you cannot know how your API will need to evolve to meet future needs. In this case, you would end up changing the API response entirely, by being forced to turn it into an object.

For example, this is how the new response will look like:

```json
{
  "result": ["Maria", "John", "Laura"],
  "averageAge": 37
}
```

This little change will force any developer who called that API to update their code accordingly. This is because the array originally returned by the API is now stored in the `result` field, which did not appear in the old response.

The problem lies in the original API response, which should always be an object. Particularly, by producing a response as follows, no developer will have to change their logic when a new field is added.

```json
{
  "result": ["Maria", "John", "Laura"]
}
```

## There Are Other Data Formats Besides JSON

JSON is the data format you normally want to use. At the same time, you have to keep in mind that there are many possible [MIME types](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) the [`Content-Type`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) HTTP header can take. `application/json` is not the only one available.

In detail, you may be asked to retrieve some data and produce a plain text file or a structured file, such as a CSV file. This actually happened to me, as described in [this](https://writech.run/blog/returning-csv-content-from-an-api-in-spring-boot-63ea82bbcf0f) article.  

In such a scenario, your approach might be to develop an API returning the required data in JSON. Then, let the caller deal with the process of transforming it to the desired format. Although there are no mistakes in this approach, it is not the best one.

You should not separate the data retrieval process from the data transformation process, just to keep your API more standard. Since you can directly return the data structured in the desired format, you should develop a custom API to achieve this.

Even though this API may seem unconventional compared to others, it will serve your needs straightforwardly. Also, having the entire logic in one place would be more elegant and maintainable.

## Do Not Omit `null` Values

[As stated in the](https://writech.run/blog/returning-csv-content-from-an-api-in-spring-boot-63ea82bbcf0f) [ECMA-404](https://www.ecma-international.org/publications-and-standards/standards/ecma-404/) standard, `null` is a valid JSON value.

> A _value_ can be a _string_ in double quotes, or a _number_, or true or false or null, or an _object_ or an _array —_ [Introducing JSON](https://www.json.org/json-en.html)

Developers are usually tempted to filter all `null` values from their responses to make them lighter. This is not inherently wrong, especially if performance and network usage are a priority. In fact, the larger the JSON, the more time needs to be spent downloading it and then parsing it.

On the other hand, omitting `null` values from your JSON response should not be the preferred approach.

First, because `null` and missing values have two different meanings in JSON. The first means "no value", while the second means "no given value"_._ Specifically, this is the same difference that there is between [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null) and [`undefined`](https://developer.mozilla.org/en-US/docs/Glossary/undefined), if you are familiar with JavaScript. The difference is subtle, but being able to distinguish between these two nuances may be crucial.

Second, returning a response whose fields change based on their value can easily confuse developers calling the API. The reason is that APIs should always be consistent in their response. Not adhering to this principle can easily lead to frustration, and also make the debugging process more complex.

Third, missing values introduce unnecessary uncertainty. The developer calling the API will likely wonder why some fields were omitted. Since figuring out whether it was intentional or not may not be easy, this would lead to unwanted doubts.

## Conclusion

Finding the right response for your API is tricky and depends on your needs. Yet, there are a few tips that can allow you to avoid future headaches due to old bad decisions. Here we looked at what I consider to be the 3 most significant tips on API responses, backed by my experience as a senior backend developer. I have been using them with success for a long time, and I wish I had known them before writing my first API.

Thanks for reading! I hope that you found my story helpful.
  
***
_The post "[3 Tips on API Responses for Backend Developers](https://writech.run/blog/3-tips-on-api-responses-for-backend-developers-8df31c23882e/)" appeared first on [Writech](https://writech.run)._