DEV Community

Cover image for Reshaping the request and response body when dealing with APIs
Ahmed Yagoub
Ahmed Yagoub

Posted on

Reshaping the request and response body when dealing with APIs

As frontend developers, we interact with APIs that helps communicate with the backend. Those APIs could be external, where we need a service from a third party provider. They could also be internal, built by the backend team in the same company you are working at.

We send information to those APIs from the frontend in the body of the request and receive information in the body of the response.

Often, the request body needs to be in a certain format that the API expects. As in the frontend, we need the response from the API to be in a format that works well in the frontend.

We are not constraint by the format of the data we receive. And so we need to reshape that format.

Array.map()

The array method .map() helps us accomplish that. It basically takes an array and produces a different array as a result. So, we can produce an array of different shape.

Here, is an example of how the .map() works

const array = [1, 2, 3];

const newArray = array.map((x) => x + 3);
Enter fullscreen mode Exit fullscreen mode

I could take an array of objects, and it would produce an array of strings. Or it takes an array of objects, and it produces an array of objects with different properties.

All depending on the callback function that you provide.

When receiving data, we want to know the format of it, and when sending data, we need to know how the request body should be formatted. Then use .map() to do the magic.

Top comments (0)