How To Use An API with Java (The Complete Beginner’s Guide)

JAVA API

In this article, we will talk about the best technology of the interaction between software and test it on the most popular language for creating software.

What is Java REST API?

This is a tough question so we’ll divide it into a few parts. Java is one of the most popular programming languages in the world. According to the TIOBE ranking (which orders languages by their popularity index), it’s actually the most popular. There are many reasons for it, but we prefer the thesis that Java is widespread, easy-to-deploy, and has a “write once, run everywhere” magic toolbox.

Are you looking to build an API instead? Check out How to Create an API in Java

Okay, but what is exactly is an API?

In short, it’s a set of rules that controls the interaction between software (i.e., an object that receives some task and object that gives this task). APIs allows us to skip diving deeply in the source code of some third-side software while allowing us to use their privileges fast and easy.

How does this interface work?

First and foremost, an API should have a host-URL (or base URL), which is the main address with which you will interact with.

Also, APIs has a predefined set of endpoints – unique addresses inside host-URL, responsible for their functionality. Furthermore, APIs should have documentation that explains all endpoints, types of returned values, etc.

After you find an interesting API and read documentation, you have to send a request – one single task for the server (receiving side).

Metaphorically, it’s like a conversation between two people: Someone (you) asks a question (request), and the interlocutor (endpoint) answers (response).

Types of API Requests

There are many different types of requests that API could handle, but here are the most used ones:

Okay, we have got the meaning of the first and the last word in “Java REST API”.

But what does REST mean?

This is the style of software communication that helps a client to get the required data in the well-state for representation (REST – representational state transfer).

So when we say REST API, we mean – APIs that not only returns requested data but also prepares it for further work.

But how can we create a RESTful API? All that is required – a bunch of the architectural constraints:

Now that we have all the information about Java RESTful APIs, Let’s try it out!

Prerequisites

First, you’ll need to have Java installed on your machine.

Also, you should have a Maven package builder for easy installing and using site-packages. Other than that, we will only need the Unirest library for making requests with no problems and in a few lines.

Here you can look at the example of code that makes a request by standard modules:

URLConnection connection = new URL(“/?param1=value1¶m2=value2”).openConnection(); connection.setRequestProperty("header1", header1); connection.setRequestProperty("header2", header2); //Get Response InputStream is = connection.getInputStream(); System.out.println(connection.getContentType());

Looks pretty difficult, right? Especially InputStream as a type of returned value (it should be further processed).

Let’s look at the same example with Unirest:

HttpResponse httpResponse = Unirest.get(“/?param1=value1¶m2=value2”) .header("header1", header1) .header("header2", header2); .asString(); System.out.println( httpResponse.getHeaders().get("Content-Type"));

Voila! You could assign the expected type of response and work with it right away.

You can use Unirest with the help of Maven, then create a Java Maven project and find the pom.xml file – it shows all dependencies and tools of the project. Insert next part of XML code in the tag:

 com.mashape.unirest unirest-java 1.4.9  

More detailed info about dependencies may be found here.

Now you can build your project by next command in terminal (be careful, use it only in the main folder, because pom.xml should be visible for Maven):
mvn package

Now you’re ready to for using Java to interact with APIs.

Overview

Before we get started, we’ll need to find an easy API to test. Sometimes it is difficult to find free and useful API for testing purposes. At RapidAPI, you’ll find over 10,000 APIs to test and connect with. Here you can test your programming skills, build useful apps, and even create your own APIs.

How to Start Using APIs with Java

1. Sign Up for RapidAPI

As mentioned before, RapidAPI has over 10,000 APIs to get started with. And with over 1 million developers using its platform, it’s one of the most popular and trustworthy API platforms.

RapidAPI Free API Key

2. Find an API

Now that you have a user account, let’s find an API to play with.

On RapidAPI.com, you can find APIs by browsing:

Let’s try searching for the IMDb API to get some info about TV and movies:

RapidAPI Search IMDb API

3. Subscribe to the API

To begin using this API, you’ll have to first subscribe to it. (Hint: there’s a freemium plan that allows for 1000 free API requests/day). You’ll be required to enter your credit card in case you incur overages.

Once you’re subscribed, you’re now ready to test the endpoints.

4. Test the Endpoints

Let’s explore all endpoints that are in this API. Look on the left side of the API page:

IMDb API documentation and endpoints

The IMDb API has only two endpoints:

  1. GET By Search – search the IMDb database by query string
  2. GET By ID or Title – get more detailed information about a specific title (includes info about the movie/tv, cast, production, and more).

On either of the API endpoints, fill out any required parameters and click “Test Endpoint”.

On the right side, you can see the snippet part, where developers show how to connect to this API with any supported language.

For this API, we need to add two headers (API unique name and our own RapidAPI token). All other params are depending on concrete endpoint. Let’s explore all endpoints that are in this API. Look on the left side of the main page.

5. Retrieve data using the API

Okay, be ready, it’s time for coding. Let’s find out everything about some famous movie that exists inside of imdb data. Return to your code and import the next things:

import java.net.URLEncoder; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.Unirest;

Here we import URLEncoder for preparing params to be sent, and 3 required objects from the Unirest library:

  1. for handling a response (HttpResponse),
  2. assigning JSON-type to it (JsonNode),
  3. and making a GET request (Unirest).

Now let’s create your main class, where all the code will be:

public class App < public static void main( String[] args ) throws Exception < //Here will be your code >>

Don’t forget about Exception. You should handle all warnings and errors for improving the project.

Okay, now let’s create a few string variables for automating some processes:

// Host url String host = "https://movie-database-imdb-alternative.p.rapidapi.com/"; String charset = "UTF-8"; // Headers for a request String x_rapidapi_host = "movie-database-imdb-alternative.p.rapidapi.com"; String x_rapidapi_key = ;//Type here your key // Params String s = "Pulp"; // Format query for preventing encoding problems String query = String.format("s=%s", URLEncoder.encode(s, charset));

Now that we’ve created the query, let’s send a request and handle the response:

HttpResponse response = Unirest.get(host + "?" + query) .header("x-rapidapi-host", x_rapidapi_host) .header("x-rapidapi-key", x_rapidapi_key) .asJson(); System.out.println(response.getStatus()); System.out.println(response.getHeaders().get("Content-Type"));

As you can see, it’s pretty simple.

For creating a request, use an Unirest library with the GET function.

Pay attention to the headers – we can add them by using dots for splitting.

After making a request and handling its response by the HttpResponse object, we can see the result.

First println shows the status code of the response – a short number that explains the situation with our requested actions.

In our case, if all is fine, it should return a 200 – OK status.

The second println , in turn, shows one of the response headers – “Content-Type”.

Let’s see what we should get with built-in API console in RapidAPI. Just input your query in the form fields and click on “Test Endpoint”:

IMDb API Test Result

You should see the same result as seen in the screenshot above.

Now, let’s check our code. Run your program, and you should see:

200 [application/json; charset=utf-8]

6. Get a JSON response

In the previous code section, we used a JsonNode object for assigning JSON format type to the response.

IMDb API JSON Response


The problem is that default JsonNode object prints data in a single row, which is rather difficult to understand. Let’s add one library for prettifying data – GSON. Modify your pom.xml file with next dependency:

 com.google.code.gson gson 2.8.5 

Now let’s add some import lines in the import section of your *.java file:

import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonParser;

These objects will help us in pretty-print our JSON. Okay, now we can call the endpoint and get a response:

// Host, charset and headers vars should be the same String i = "tt0110912"; // Format query for preventing encoding problems query = String.format("i=%s", URLEncoder.encode(i, charset)); // Json response HttpResponse response = Unirest.get(host + "?" + query) .header("x-rapidapi-host", x_rapidapi_host) .header("x-rapidapi-key", x_rapidapi_key) .asJson(); //Prettifying Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonParser jp = new JsonParser(); JsonElement je = jp.parse(response.getBody().toString()); String prettyJsonString = gson.toJson(je); System.out.println(prettyJsonString);

If all goes well, we should see the following response:

< "Metascore": "94", "BoxOffice": "N/A", "Website": "N/A", "imdbRating": "8.9", "imdbVotes": "1,655,375", "Ratings": [ < "Value": "8.9/10", "Source": "Internet Movie Database" >, < "Value": "92%", "Source": "Rotten Tomatoes" >, < "Value": "94/100", "Source": "Metacritic" >], "Runtime": "154 min", "Language": "English, Spanish, French", "Rated": "R", "Production": "Miramax Films", "Released": "14 Oct 1994", "imdbID": "tt0110912", "Plot": "The lives of two mob hitmen, a boxer, a gangster and his wife, and a pair of diner bandits intertwine in four tales of violence and redemption.", "Director": "Quentin Tarantino", "Title": "Pulp Fiction", "Actors": "Tim Roth, Amanda Plummer, Laura Lovelace, John Travolta", "Response": "True", "Type": "movie", "Awards": "Won 1 Oscar. Another 62 wins and 69 nominations.", "DVD": "19 May 1998", "Year": "1994", "Poster": "https://m.media-amazon.com/images/M/MV5BNGNhMDIzZTUtNTBlZi00MTRlLWFjM2ItYzViMjE3YzI5MjljXkEyXkFqcGdeQXVyNzkwMjQ5NzM@._V1_SX300.jpg", "Country": "USA", "Genre": "Crime, Drama", "Writer": "Quentin Tarantino (stories), Roger Avary (stories), Quentin Tarantino" >

Example: Using Java & APIs to Display other types of Data

As you may remember, the Content-Type header of the previous requests was for “application/json”, but what if we want to send/receive something that can’t be processed in JSON?

For example, a file or image?

Let’s try demonstrating this with the Meme Generator API.

Meme Generator API consists of 5 endpoints:

Let’s use the Generate meme endpoint:

First, let’s modify our imports by adding these lines to the top of our code:

import java.io.InputStream; import java.io.File; import java.awt.image.BufferedImage; import javax.imageio.ImageIO;

Now, paste the following code snippet inside the main method:

// Host url String host = "https://ronreiter-meme-generator.p.rapidapi.com/meme"; String charset = "UTF-8"; // Headers for a request String x_rapidapi_host = "ronreiter-meme-generator.p.rapidapi.com"; String x_rapidapi_key = ; // Params String meme = "Chuck-Norris-Approves"; String top = "We made this meme with Chuck"; String bottom = "Although we weren't even connected to the internet"; String query = String.format("meme=%s&top=%s&bottom=%s", URLEncoder.encode(meme, charset), URLEncoder.encode(top, charset), URLEncoder.encode(bottom, charset)); // Meme generator HttpResponse httpResponse = Unirest.get(host + "?" + query) .header("x-rapidapi-host", x_rapidapi_host) .header("x-rapidapi-key", x_rapidapi_key) .asBinary(); //Image saving InputStream is = httpResponse.getRawBody(); BufferedImage inputStreamImage = ImageIO.read(is); File image = new File("image.jpg"); ImageIO.write(inputStreamImage, "jpg", image); System.out.println( httpResponse.getHeaders() .get("Content-Type"));

Here we handle raw body of the response into the InputStream object. Next step is to read it in the BufferedImage object – dynamic image in the memory of the program.

Finally, let’s create (or update) an image.jpg file and save buffer inside it. This should output the following:

[image/jpeg]

As you may see, API returns to an image object.

To see the actual image, let’s check the main folder of our project and you should find:

Chuck Norris Meme made by <a href=Meme Generator API" width="611" height="396" />

Conclusion

In this guide, we studied how to use RapidAPI for making an exciting and useful Java REST API applications and tried a few helpful APIs for clearing key moments in this technique.

Related Resources

Related Tutorials

FAQ

How can you create an API in Java?

Check out these Java API Tutorials on how to create an API.

Is Java an API?

APIs are a set of definitions and protocols that allow technology products and services to communicate with each other.

A Java Application Programming Interface (API) can refer to the Java development kit (JDK) or APIs that are accessible using Java.

Is JSON an API?

JSON or JavaScript Object Notation is an encoding scheme that is designed to eliminate the need for an ad-hoc code for each application to communicate with servers that communicate in a defined way. JSON API module exposes an implementation for data stores and data structures, such as entity types, bundles, and fields. – Source