Apidog

All-in-one Collaborative API Development Platform

API Design

API Documentation

API Debugging

API Mock

API Automated Testing

Sign up for free
Home / Tutorials / Guide to: UniRest for NodeJS

Guide to: UniRest for NodeJS

Developers using Node.JS can now utilize UniRest's lightweight framework! With the simplification of making HTTP requests and handling asynchronous tasks efficiently, find out how you can start using UniRest in PHP!

UniRest is an HTTP request library that has gained much popularity recently. While being known for its flexibility and simplicity of use, you can easily make HTTP requests with a concise and readable syntax. Together with NodeJS, developers are enabled to use JavaScript for server-side and command-line applications, expanding the scope of applications that they can create.

💡
A vivid NodeJS developer looking for an API development platform to host your project development? Look no further - introducing Apidog, a comprehensive API tool that equips developers with all the necessary tools for building, testing, mocking, and documenting APIs.

To learn more about what other functionalities Apidog has to offer, make sure to click the button below!
Apidog An integrated platform for API design, debugging, development, mock, and testing
REAL API Design-first Development Platform. Design. Debug. Test. Document. Mock. Build APIs Faster & Together.
button

What is UniRest?

UniRest is a lightweight HTTP request client library available in multiple programming languages, including NodeJS, simplifying the process of interacting with APIs (Application Programming Interfaces) within your code. You can also think of UniRest as a translator that enables your apps to communicate with other web services.

What does the "NodeJS" in "UniRest NodeJS" Mean?

unirest nodejs github

Whenever you see NodeJS in the phrase "UniRest NodeJS", it refers to the NodeJS JavaScript runtime environment, as the UniRest library now supports NodeJS projects.

UniRest NodeJS Key Features

The UniRest NodeJS library can be an excellent framework for applications due to a set of notable features it provides developers with, such as:

GitHub - Kong/unirest-nodejs: Unirest in Node.js: Simplified, lightweight HTTP client library.
Unirest in Node.js: Simplified, lightweight HTTP client library. - Kong/unirest-nodejs

Concise and Readable Syntax

UniRest NodeJS offers a chainable API that makes constructing HTTP requests intuitive. You can easily define the method (GET, POST, PUT, etc.), URL, headers, and body with clear function calls. This reduces boilerplate code and improves readability

Supports Various HTTP Methods

UniRest NodeJS handles all standard HTTP methods like GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS. This flexibility allows you to interact with APIs that require different operations for data retrieval, creation, or modification.

Automatic JSON Handling

UniRest NodeJS automatically parses JSON responses into JavaScript objects, eliminating the need for manual parsing. This streamlines the process of working with JSON data returned by APIs.

Promise-Based Requests

UniRest NodeJS utilizes Promises for asynchronous requests, allowing you to handle responses in a non-blocking manner. This improves code flow and avoids callback hell, making your code cleaner and easier to maintain.

Built-in Interceptors

UniRest NodeJS offers interceptors for error handling and authentication. These interceptors act as middleware, allowing you to define actions to be taken before a request is sent or after a response is received. This simplifies error handling and streamlines authentication processes.

Customizable Timeouts and Concurrency

You can configure timeouts for requests to prevent them from hanging indefinitely. Additionally, UniRest NodeJS allows setting concurrency levels, controlling how many requests can be sent simultaneously. This helps manage network resources and performance.

Default Headers and HttpClient Customization

UniRest NodeJS allows setting default headers for every request, reducing repetitive code. You can also customize the underlying HttpClient implementation used by UniRest NodeJS, providing greater control over network behavior.

By leveraging these features, UniRest empowers developers to interact with APIs efficiently and write cleaner, more maintainable NodeJS code.

How to Install UniRest NodeJS?

unirest nodejs github website

There are a few steps developers need to take before they can start using UniRest NodeJS in their applications.

Using NPM to Install UniRest in NodeJS

Inside your project directory, open your terminal or command prompt and type in this line of code to install UniRest. This utilizes npm (Node Package Manager).

npm install unirest

Making a GET Request with UniRest in NodeJS

UniRest can simplify the process of sending requests to APIs in your NodeJS applications. Here is a step-by-step process for sending a GET request.

//improting UniRest into your Node.JS file
const unirest = require('unirest');

You will first need to import UniRest into your NodeJS file by using the statement above inside your NodeJS project directory terminal.

const url = 'https://api.example.com/data';

unirest.get(url)
  .headers({ 'Accept': 'application/json' })  // Optional headers
  .end((response) => {
    if (response.error) {
      console.error('Error:', response.error);
    } else {
      console.log('Response:', response.body);
    }
  });

Proceed by utilizing UniRest's get method to define the GET request. An example of this would be the lines of code above.

In the code snippet above, there are a few variables that might be unfamiliar to you, such as:

url: This specifies the API endpoint you want to retrieve data from.

.headers(): Although optional, this line allows you to set additional headers for the request. In the code snippet above, a header would be Accept.

.end(): This method sends the GET request asynchronously and takes a callback function as an argument.

response.error: The property that contains any error information if the request fails, allowing developers to notify what went wrong.

response.body: The property that holds the response body (which is usually JSON data) if the request is successful.

To finish and run your NodeJS project, save the code in a .js file and run it.

Apidog - Generate JavaScript Code In Seconds

NodeJS projects are made with the JavaScript programming language. Developers who are interested in using UniRest for NodeJS are therefore expected to have prior knowledge of JavaScript. However, with Apidog - an all-in-one API development platform - you no longer need to spend time figuring out JavaScript.

apidog mock interface
button

Apidog has a client code generation feature that enables developers to quickly produce and implement code.

Generating JavaScript UniRest Code with Apidog

Download the Apidog application and create a new project.

apidog generate client code

First, locate the </> button found around the top right corner of the screen. If you are struggling to locate the button, you can refer to the image above.

apidog generate javascript unirest code

Proceed by selecting the client-side programming language that you need. As this article discusses UniRest for NodeJS, a demonstration of code generation for JavaScript specialized in the UniRest library will be shown.

All you need to do is copy and paste the code to your IDE, and continue with editing to ensure it fits your NodeJS app!

button

Test Out APIs with Apidog

Apidog provides developers with a comfortable yet beautiful user interface for debugging APIs.

Provide the API endpoint in the bar highlighted by the arrow in the image above.

If you're unsure about using multiple parameters in a URL, this article can guide you on how to hit the exact resource within larger datasets!

Tutorial: How to Pass Multiple Parameters in REST API URLs?
Two commonly seen parameter types are widely used in modern websites. Although they slightly differ based on their functions, parameters help developers identify specific resources found within a collection or system.
apidog response view

Once you are sure of your API, you can click Send, which sends the request to the API. You should expect a complete response. A glance at the status code tells you if it was successful. You can also examine the raw response, which shows the exact data structure your code needs to understand the information from the API's servers.

button

Conclusion

UniRest emerges as a valuable tool for NodeJS developers seeking to streamline API interactions. Its concise syntax and chainable API make crafting HTTP requests a breeze. Automatic JSON handling and promise-based requests further enhance the development experience. Built-in features like interceptors and customizable timeouts empower developers to manage errors, authentication, and network behavior effectively. By leveraging UniRest, developers can focus on the core functionalities of their applications, leaving the complexities of HTTP communication to this versatile library.

If you plan to build NodeJS applications that interact with APIs, UniRest is a strong contender for your HTTP client library. Its ease of use, comprehensive features, and focus on developer experience make it a valuable asset for efficient and maintainable code. Explore UniRest's capabilities and discover how it can simplify your API interactions in the world of NodeJS development.

Join Apidog's Newsletter

Subscribe to stay updated and receive the latest viewpoints anytime.