In this tutorial I’ll be using a website called RapidApi.com which is a great site for quickly connecting to various api’s.
- Step one is creating an account on RapidApi. You should be able to connect using google or facebook auth.
- Next, if you don’t already have a project you are planning on using the api with, you will need to create one.. obviously.
- Now, back to the site, pick out an api that looks interesting or useful to your application. I recommend finding one with a free version just to make sure you like it. For this tutorial I’ll be using an api called CoinRank.
- On the api’s main page change the dropdown to “Java Unirest”. This will auto generate the response block we will use to communicate with the api. (Note: I have whited out my api key because I am using this in a current project)
- In order to use this premade code we need to add .jar files for both unirest and json to our projects library. First go to this link for unirest, download the .jar file and put it in a folder in your project. This can be a folder named “lib” for example. Next do the same with this link for json.
- The next step differs slightly depending on whether you are using netbeans, eclipse or some other IDE. We need to add the .jars to our project library. In Netbeans you right click your project in the left explorer –> Properties –> Libraries –> Add JAR/Folder, then select both of the .jar files you downloaded. (Note: in Netbeans 12 you need to click the button with three dots on it to access the Add JAR button).
- Now you just need to copy the code over from rapidapi into your project. I recomment creating a class whose only job is to connect a model / class to a corresponding api. You can think of it as a telephone switching station. It gets a call, directs it to the correct endpoint, then returns the response. This is what I came up with to do just that.
-
public ConnectToApi(String _url, String _endpoint, String _key) { HttpResponse<JsonNode> resp; try { resp = Unirest.get(_url) .header("x-rapidapi-host", _endpoint) .header("x-rapidapi-key", _key) .asJson(); this.status = true; if (resp.getStatus() != 200) { this.status = false; } if (DEBUG) {System.out.println("Status: " + resp.getStatus());} this.response = resp.getBody().toString(); this.job = new JSONObject(resp.getBody().toString()); } catch (UnirestException ex) { Logger.getLogger(ConnectToApi.class.getName()).log(Level.SEVERE, null, ex); } }
- This is a constructor for a class called ‘ConnectToApi’. The parameters it takes are: _url, the url of the api; _endpoint, the specific api point you want to get data from; and _key, the autogenerated key you use to authenticate with the api. We store the response in a HttpResponse object made up of json text. After the unirest call I check the response status and save it in a variable. This is important for preventing the failure of an api from breaking your program. And then finally I store the response as string and as a json object which can be accessed using getter methods.
A few notes: Be sure to take a look at the optional parameters you can send in the api url. Sometimes you will be able to send different values to get different results.
If you are interested here is the full ConnectToApi.java class:
import interfaces.ApiInterface; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import java.util.logging.Level; import java.util.logging.Logger; import org.json.JSONObject; public class ConnectToApi implements ApiInterface{ private JSONObject job; private String response; private boolean status; private final boolean DEBUG = controllers.Tab1Controller.DEBUG; /** * Create a generic connection to a given api. * @param _url * @param _endpoint * @param _key */ public ConnectToApi(String _url, String _endpoint, String _key) { HttpResponse<JsonNode> resp; try { resp = Unirest.get(_url) .header("x-rapidapi-host", _endpoint) .header("x-rapidapi-key", _key) .asJson(); this.status = true; if (resp.getStatus() != 200) { this.status = false; } if (DEBUG) {System.out.println("Status: " + resp.getStatus());} this.response = resp.getBody().toString(); this.job = new JSONObject(resp.getBody().toString()); } catch (UnirestException ex) { Logger.getLogger(ConnectToApi.class.getName()).log(Level.SEVERE, null, ex); } } // ========== GETTERS ========== // @Override public JSONObject getJsonObject() { return this.job; } @Override public String getResponseString() { return this.response; } @Override public boolean getStatus() { return this.status; } }