Java API Tutorials

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

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.

Browse the Best Free APIs List

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?

Well, API stands for Application Programming Interface.

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:

  • GET – returns data from the server. The most popular request by the way.
  • POST – adds new data on the server. Often this type is used for registration or uploading files.
  • PUT/PATCH – updates data, useful request but not so sought-after.
  • DELETE – removes data from the server.

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:

  • Client-server architecture – clear separation on two sides. The client sends requests and waits for the answer; the server then takes the opposite role. The main reason for this constraint – one side doesn’t care about anything except the correct format of the interaction (it’s not your problem how the server performs your request and vice versa).
  • Statelessness – independence of each singular request from all previous and future requests. For example, if you would send the question “What Charlie’s surname?”, and then follow up with “How old is he?”, the server wouldn’t be able to answer the latter. The server doesn’t save any information from the client and requires it in each request.
  • Cacheability – instead of the server, the client could (and even should) save some data on the local storage (cache). It increases productivity, as far as the number of requests will be smaller.
  • Layered system – the server should include layers for different parts of the process. It is useful because layers don’t know anything about each other and server could easily be scaled with new layers (e.g., security).
  • Uniform interface – each endpoint has to be with a unique address. Simple, useful, and necessary.

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(“<some_url>/<endpoint>?param1=value1&param2=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 <String> httpResponse = Unirest.get(“<some_url>/<endpoint>?param1=value1&param2=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 <dependencies> tag:

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

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.

So click here to get started, it’s free.

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:

  • Categories (example: Gaming APIs)
  • Search
  • Curated Collections on the Homepage

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

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.

If you want to try some free APIs (without credit card) instead, browse this collection.

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:

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 = <YOUR_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 <JsonNode> 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”:

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.


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:

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.8.5</version>
</dependency>

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 <JsonNode> 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:

  • Generate meme
  • Get fonts
  • Upload Image
  • Upload font
  • Get images

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 = <YOUR_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:

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?

Java is a programming language.

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

Browse the Best Free APIs List

3.4/5 - (7 votes)

View Comments

  • I have copied the java-okhttp code from API , now wanted to filter specific data from some responses,how to do that?
    package rapidapi;

    import java.io.IOException;

    import okhttp3.Headers;
    import okhttp3.OkHttpClient;
    import okhttp3.Request;
    import okhttp3.Response;

    public class RapidapiExample {

    public static void main(String[] args) {
    // TODO Auto-generated method stub

    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
    .url("https://imdb8.p.rapidapi.com/title/auto-complete?q=game%20of%20thrones")
    .get()
    .addHeader("x-rapidapi-key", "b7a78b955emsh8e8b0eb38f2afc5p19f52ajsn8fe4ad5f0ab8")
    .addHeader("x-rapidapi-host", "imdb8.p.rapidapi.com")

    .build();

    try {
    Response response = client.newCall(request).execute();

    /*
    * if (!response.isSuccessful()) throw new IOException("Unexpected code " +
    * response);
    *
    * // Get response headers Headers responseHeaders = response.headers(); for
    * (int i = 0; i < responseHeaders.size(); i++) {
    * System.out.println(responseHeaders.name(i) + ": " +
    * responseHeaders.value(i)); }
    */
    System.out.println(response.body().string());
    System.out.println(response);
    System.out.println(response.code());

    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    }

    }

  • i'm a newbie, but i really appreciate the code that you uploaded to this site. Cheers!

Share
Published by

Recent Posts

Power Up Your Enterprise Hub: New March Release Boosts Admin Capabilities and Streamlines Integrations

We're thrilled to announce the latest update to the Rapid Enterprise API Hub (version 2024.3)!…

3 weeks ago

Unveiling User Intent: How Search Term Insights Can Empower Your Enterprise API Hub

Are you curious about what your API consumers are searching for? Is your Hub effectively…

3 weeks ago

Rapid Enterprise API Hub Levels Up Custom Branding, Monetization, and Management in February Release

The RapidAPI team is excited to announce the February 2024 update (version 2024.2) for the…

1 month ago

Supercharge Your Enterprise Hub with January’s Release: Search Insights, Login Flexibility, and More!

This January's release brings exciting features and improvements designed to empower you and your developers.…

3 months ago

Enhanced Functionality and Improved User Experience with the Rapid API Enterprise Hub November 2023 Release

Rapid API is committed to providing its users with the best possible experience, and the…

5 months ago

The Power of Supporting Multiple API Gateways in an API Marketplace Platform

In today's fast-paced digital world, APIs (Application Programming Interfaces) have become the backbone of modern…

6 months ago