Apidog

All-in-one Collaborative API Development Platform

API Design

API Documentation

API Debugging

API Mock

API Automated Testing

Sign up for free
Home / Viewpoint / Everything You Must Know About UniRest Java

Everything You Must Know About UniRest Java

UniRest is a collection of open-source, lightweight libraries for various programming languages, simplifying making HTTP requests to web services.

UniRest is a suite of open-source libraries specifically designed to simplify HTTP (Hypertext Transfer Protocol) communication for various programming languages, such as Python, Java, and .NET.

💡
UniRest is a lightweight HTTP client library that enables developers to test for API HTTP requests. Therefore, you should have the proper tools ready to view and modify APIs.

An API development platform worth considering is Apidog, a one-stop solution for your API problems. With Apidog, you can not only view API responses, but also modify its body, test it out, and ensure everything goes smoothly.

To learn more about Apidog, 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?

kong github

UniRest is known as a powerful open-source toolkit aimed at alleviating the complexities associated with HTTP interactions within the software development realm. Encompassing libraries designed for numerous programming languages, including Python, Java, and .NET, UniRest simplifies the process of crafting HTTP requests and handling responses.

UniRest achieves its goals through a user-centric interface that streamlines tasks like sending data, managing JSON payloads, and facilitating asynchronous communication. By offering a more efficient approach to HTTP interactions, UniRest empowers developers to expedite development cycles and produce applications with enhanced communication capabilities.

What is UniRest For?

Developers look for UniRest in scenarios such as:

Building Web Applications

UniRest simplifies communication between your application and various web services, such as fetching user data from backend servers or sending information to a payment gateway. UniRest handles the HTTP requests and responses, allowing you to focus on the application logic.

Consuming APIs

Many modern applications rely on APIs (Application Programming Interfaces) to access data and functionality. UniRest conveniently provides a way to interact with these APIs, allowing developers to send requests with specific parameters and handle the received data seamlessly.

Data Integration

UniRest excels at integrating data from different sources, such as pulling product information from an e-commerce platform or retrieving weather data from a weather API. UniRest facilitates these data transfers, enabling developers to combine information from various sources within their applications.

Testing Web Services

UniRest is a valuable tool for testing web services. Developers use it to simulate different types of requests and verify the expected responses, ensuring web services function as intended.

How to Set Up UniRest?

There are a few steps to take before you can utilize the UniRest client library.

For this article, we will be using the Java programming language.

Maven Set Up

First, add the necessary dependencies to your client-side code. It should look like this:

<dependency>
    <groupId>com.mashape.unirest</groupId>
    <artifactId>unirest-java</artifactId>
    <version>1.4.9</version>
</dependency>

Send HTTP Requests

To get familiar with the UniRest framework, take a look at this simple HTTP request example:

Simple Version

@Test
public void shouldReturnStatusOkay() {
    HttpResponse<JsonNode> jsonResponse 
      = Unirest.get("http://www.mocky.io/v2/5a9ce37b3100004f00ab5154")
      .header("accept", "application/json").queryString("apiKey", "123")
      .asJson();

    assertNotNull(jsonResponse.getBody());
    assertEquals(200, jsonResponse.getStatus());
}

However, APIs can be more complex, involving more elements such as headers and parameters. To pass these variables in the request, you can create a map, as shown in the code snippet below:

Complex Version

@Test
public void shouldReturnStatusAccepted() {
    Map<String, String> headers = new HashMap<>();
    headers.put("accept", "application/json");
    headers.put("Authorization", "Bearer 5a9ce37b3100004f00ab5154");

    Map<String, Object> fields = new HashMap<>();
    fields.put("name", "Sam Baeldung");
    fields.put("id", "PSP123");

    HttpResponse<JsonNode> jsonResponse 
      = Unirest.put("http://www.mocky.io/v2/5a9ce7853100002a00ab515e")
      .headers(headers).fields(fields)
      .asJson();
 
    assertNotNull(jsonResponse.getBody());
    assertEquals(202, jsonResponse.getStatus());
}

List of UniRest Request Methods

UniRest provides separate methods for each HTTP method available.

UniRest POST Method

Unirest.post("insert endpoint here")

UniRest PUT Method

Unirest.put("insert endpoint here")

UniRest GET Method

Unirest.get("insert endpoint here")

UniRest DELETE Method

Unirest.delete("insert endpoint here")

UniRest PATCH Method

Unirest.patch("insert endpoint here")

UniRest OPTIONS Method

Unirest.options("insert endpoint here")

Extracting Response Data

UniRest provides a solution to extract the API response in the form of functions via the client code.

Status Code and Message

jsonResponse.getStatus()

Headers

jsonResponse.getHeaders();

Response Body

//returns a parsed body
jsonResponse.getBody();

//returns an unparsed response
jsonResponse.getRawBody();

Speed Up Code Development with Apidog

Since UniRest has its libraries implemented in various programming languages, it is essential that you understand how to create the code so you can interact with APIs. Thankfully, there is an API tool called Apidog that is capable of generating client side code within seconds.

apidog interface
button

Aside from generating relevant client code, Apidog provides developers with all the necessary tools needed for designing, testing, mocking, and documenting APIs. Let's check out how Apidog can provide value to developers!

Generating Java Client Code with Apidog

Apidog provides developers with a simple yet intuitive user interface, allowing fast adaptation to a new development environment.

generate client code apidog

First, make sure to have Apidog downloaded, and that you have created a new project. You can begin the process of generating the client code by finding the </> button around the top right corner of the Apidog window.

apidog generate java code

Next, select the programming language you wish to generate code for. As this article revolves around the UniRest framework in Java, we shall generate Java code. Now, all you need to do is copy and paste the code into your IDE (Integrated Development Environment)!

button

Test Previously Made APIs with Apidog

Do you have other APIs that you wish to test before publishing or sharing with other people? If your answer is yes, come check out how you can quickly test your APIs with Apidog!

Start out by providing the API's endpoint in the bar above, as pointed out by the arrow in the picture above, Make sure to include any additional details required by that specific endpoint (these are called parameters).

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 compelling solution for developers seeking to streamline HTTP interactions within their projects. By offering a suite of open-source libraries compatible with various programming languages, UniRest empowers developers to construct efficient and robust applications.

Its ability to simplify data transmission, API consumption, and asynchronous communication translates to faster development cycles and applications capable of seamlessly interacting with external services. As the software development landscape continues to evolve, UniRest's position as a valuable toolkit for crafting modern, data-driven applications is certain to solidify.

 

Join Apidog's Newsletter

Subscribe to stay updated and receive the latest viewpoints anytime.