Build it better: API Response Mapping

Brandon Lange
3 min readOct 2, 2022

--

API Response mapping is when we convert an HTTP response to a new object in order to expose more functionality to our View Model in a more encapsulated and loosely coupled manner.

Build it better api response mapping banner

Please note that this is part of a series where I build up my new SASS business Core Supply. In the previous post we took a look at making the Next.js API request TypeSafe. so if you like this kind of real world scenario coding content, then please let me know in the comments and possibly consider following :)

API response mapper

Below is an example of a function that we might use in order to map responses from our API. This takes in two arguments. An endpoint to get the data from as well as a predicate callback function which allows us to transform the response data.

Implementation

Let’s take the idea of a todo list item to see how we can implement this as well as why this is beneficial. We will start off by imagining that we have a page with many todo list items like so:

Display wise we only need a title and a completed flag. Functionality wise we need to be able to toggle the checked value. An implementation using the fetchDataAs method would look something like this:

Let’s break this down to see why this is beneficial. Firstly we have our two different types, Todo and TodoListItem. Todo acts as the input data for our predicate function so that we can easily map our output data to a new type.

With this example we make the title and completed properties immutable so we can no longer just change them by reassigning them, but the only way that we can alter the data is by calling the toggleComplete method.

Now let’s say we can navigate to an edit page in order to update the todo’s description. This implementation, while similar will only require a means to update the title and would be implemented like this:

In this example we created a new interface that makes use of the Todo but only allows accesses to read and modify the title.

This segmentation is important to us because even though the TodoListItem and TodoEditItem make use of the same base Todo interface, they both have different reasons for existing.

By implementing this we have a complete overview of the functionality that these interfaces provide. This allows for full transparency throughout your application and a none technical person should in theory be able to read the code and understand what it can do.

If you would like more complex examples, or for me to clarify anything mentioned in this post, then please let me know in the comments and I will be sure to get back to you.

Until then… Happy Hacking!

--

--

Brandon Lange

Software developer at AboutYou. My main focus is pretty much to build cool stuff 🤟. Follow me if you feel the same way!