DEV Community

Cover image for How to Return multiple functions and values while working with REST APIs (Part 1)
Olufemi obafunmiso
Olufemi obafunmiso

Posted on

How to Return multiple functions and values while working with REST APIs (Part 1)

As a developer, you interact with REST APIs directly or indirectly, every day at work. This makes it important now more than ever to keep learning and keep improving your REST development skills.

In this part 1 of the series, I will show you how to use the q library function .spread() to specify multiple functions to use as the callbacks and explore the possibilities with this library, while in part 2, we'll not be using the q library. q library is used for creating custom promises and can be quite handy when working with promises.

We'll be exploring how to execute multiple functions at the same time and use .spread() to grab the response from each of the functions. .spread() is a q library function which can be use as a replacement for .then() .

If you have a promise for an array, you can use .spread() as a replacement for .then() The spread function β€œspreads” the values over the arguments of the fulfillment handler. The rejection handler will get called at the first sign of failure. That is, whichever of
the received promises fails first gets handled by the rejection handler. (Source:https://documentup.com/kriskowal/q/)

Here's the concept of returning multiple values and using .spread()



 return [a,b,c];
        .spread(a,b,c)=>{
        //
        }


Enter fullscreen mode Exit fullscreen mode

This comes in handy when building APIs that query multiple tables and/or calling multiple endpoints.

For the sake of this tutorial and to keep it simple, I'll be making use of chuck-norris API https://api.chucknorris.io/
This is a free JSON API for hand-curated Chuck Norris facts.

The modules used:

  • Axios : This module makes HTTP request seamless. Check it out here
  • q : This module is used for creating custom promises. Check it out here
  • Express: Fast, unopinionated, minimalist web framework for node. Check it out here

The endpoints:
In this tutorial, we'll be making requests to two chuck-norris APIs

To install all the dependencies required for this task, run npm install q axios express

Let's get our hands dirty πŸ”₯

Line 8 : q.fcall() is q library function and it is used to create a promise.

Line 13: return [joke, categories] stops the execution of the block of code and returns the HTTP request made to chuck-norris API in line 9 and 10.

Line 15: .spread() works like .then() but takes in multiple arguments unlike .then() that takes up to two arguments: callback functions for the success and failure cases of the Promise.

line 17 -18: I decide to filter the API response to what I needed. You can filter the response as you please also.

Line 22-27 : I introduced if statement logic to check if the returned response from the API contains data. This is purely me ensuring that I checked if data field is returned in the response before proceeding.

Line 31 : The reason why I decided to randomize 0-15 is because the categories API returns close to 15-16 categories info which I really don't want to expose all, I preferred to randomly pick one as my response which is what I did in Line 39. Again, this just me doing my thing πŸ˜ƒπŸ˜ƒ not really necessary. You can do as you please πŸ˜‰

Line 34-42: I decided to create and structure my response. πŸ˜‰

Line 43: Finally send back my response

Line 45-47 : I ensured I catch any error

One thing I didn't mention which might be confusing for a beginner is line 6
I choose the endpoint name as /chuck-norris based on my mood right now 😁 you can choose any name you want.

Now let's run our APP πŸš€πŸš€πŸš€

On Line 49-52 I have setup my app to run on port 3000.
I'm using nodemon on my local machine so I'm running this command; nodemon app.js [You can install nodemon as a dev dependency npm install --save-dev]

Open your Postman or Insomnia or even your browser since it's a get request
Make a request to this endpoint: http://localhost:3000/chuck-norris

Voila πŸŽ‡

Everything is working!

With q library functions , we (me and you πŸ˜‰) were able to create a promise with q.fcall() where I made two API request to chuck norris APIs and return the response of the two calls in an array and finally used .spread() which is also a q library function that takes in multiple arguments to use as the callbacks.

Happy coding 🍻

See Project here

Do you like this article? Hit me up on Twitter or linkedin

Top comments (6)

Collapse
 
leandroandrade profile image
Leandro Andrade

Thanks for this article. Do you have any particular reason for using "q" library instead a native modules like Promise? I question this because I had the same result using Promise.all instead is using "q" library. Other insigth is change Promise.all to Promise.allSettled that allow us to handle errors.

Below the code:

const axios = require("axios");
const app = require("express")();

app.get("/chuck-norris", async (req, res) => {
    try {
        const promises = ["https://api.chucknorris.io/jokes/random", "https://api.chucknorris.io/jokes/categories"]
            .map(url => axios.get(url));
        const result = await Promise.all(promises);

        const [jokeResponse, categoryResponse] = result;
        const { data: joke } = jokeResponse;
        const { data: category } = categoryResponse;

        const jokeData = joke.value;
        if (!jokeData) {
            res.send({ message: "Value of joke is not available" });
        }

        if (!category) {
            res.send({ message: "Category is not available" });
        }

        const random = Math.floor(Math.random() * 16);
        const response = {
            status: "success",
            message: "Data fetched",
            data: {
                joke: jokeData,
                categories: category[random]
            }
        };

        return res.json(response);
    } catch (err) {
        return res.json({ message: err });
    }
});

const listener = app.listen(8088, () => {
    console.log("Your app is listening on port " + listener.address().port);
});

Enter fullscreen mode Exit fullscreen mode
Collapse
 
olufemi profile image
Olufemi obafunmiso • Edited

Hi Leandro,

This is part 1.

I did mentioned that in part 2, we'll not be using the q library on line 6 of this article.

I will Publish Part 2 very soon.

I explained there how to achieve this with Javascript native functions.

Thank you for taking out time to read this article.

Collapse
 
vicradon profile image
Osinachi Chukwujama

Nice article

Do you have any particular reason for using a screenshot of code instead of using the native markdown code block?

Collapse
 
olufemi profile image
Olufemi obafunmiso

Hi @osinachi,

Thank you!

I used Screenshot because markdown on dev.to doesn't show line number.

Collapse
 
iyosayi profile image
King Etiosasere

This is actually nice!! I have been looking for ways to return multiple requests from an API call, this just showed me how to do it. Thank you very much.

Collapse
 
olufemi profile image
Olufemi obafunmiso

Hi King,

I'm glad the article was able to help.

Thanks for the feedback.