Introduction
The PeerReach API available on RapidAPI provides insight into a Twitter user’s profile information. PeerReach provides detailed context information about a user, including the user’s peer groups, followers, and subjects interesting to the user. In this tutorial, we access the PeerReach Twitter API using the UniRest and OKHttp Java libraries.
This tutorial also provides a workflow you should follow when consuming an API on RapidAPI. We first use the RapidAPI dashboard sample JSON schema combined with the online tool JSON Schema validator (JSON Schema Validator) to create a JSON schema for the PeerReach API. After creating the schema, we validate several JSON responses against the schema, modify the schema as necessary, and then generate plain old Java objects (POJOs) using the online tool jsonschema2pojo (jsonschema2pojo.org).
After creating POJOs, we call the PeerReach API using both the OkHttp Java client and the UniRest Java client using code snippets provided by the RapidAPI dashboard. As most Java applications use Java objects rather than JSON text, we modify the code provided by RapidAPI to use Jackson to deserialize the JSON into corresponding POJOs.
- In this tutorial, we deserialize JSON into Java objects rather than working with raw JSON.
Although the sample project uses SpringBoot and Maven, the Java classes are generic enough to be modified to use independently easily. The focus in this tutorial is the Java classes rather than the Spring Boot project.
- Both UniRest for Java and OkHttp are popular libraries on Android to call RestAPIs. The code in this tutorial, with minimal modification, applies to Android development.
Using PeerReach API to get Twitter Data
The PeerReach API allows looking up and getting a detailed summary of a user’s Twitter activity. It returns a JSON response containing a user’s basic information, profiles, and peer groups belonged. Information provided by the API includes,
- last update date,
- number of followers,
- the user’s country and gender,
- the user’s interests,
- the user’s profiles,
- the user’s peer groups,
- and the subjects that interest the user.
Your organization can use this information independently or combine this API into a more extensive solution. Regardless, if you wish greater insight into Twitter users, the PeerReach API is a useful API that wraps the Twitter API with a more easily used API for accessing a user’s profile information.
Step One: Subscribe to the PeerReach Twitter API
Before connecting to the PeerReach API, decide if you wish to subscribe to the free API or the premium API. The free API is limited to 2400 rest calls per day and requires no subscription, while the professional API has no such limitation. The professional API requires a standard RapidAPI subscription where the costs are,
- 2400 calls per day are free,
- 10000 requests per day are $70 per month,
- 50,000 calls per day are $295 per month,
- and 250,000 requests per day are $1,250 per month.
In this tutorial, we use the premium version of the PeerReach API. However, due to the small number of calls made while writing this tutorial, despite subscribing, it remains free. Unless you start using the API in production, you should easily stay under the 2400 daily limit.
Step Two: Test the Endpoint
After subscribing to the endpoint, we first explore/test the endpoint directly in the RapidAPI dashboard. The RapidAPI dashboard provides an example JSON response, JSON schema, and a way to check using your data. Simply replace the screen_name
parameter with another value, click Test Endpoint
, and then view the results in the Body
tab.
- Enter MikeTyson in the
screen_name
parameter text box. - Click
Test Endpoint
. - Review the
Body
andHeaders
in theResults
tab.
It might be tempting at this point to begin developing your client application that consumes the endpoint. However, starting development would be premature, as we have not robustly examined the endpoint. To thoroughly test the endpoint, we should make calls using a tool such as curl and ensure the JSON response conforms to the JSON schema. A little more time spent testing the API can prevent hours of reworking client software. Only after thoroughly testing the API can we be reasonably assured we understand the API enough to write robust client software. And also, remember, the API provider, and not RapidAPI, is responsible for updating his or her endpoints in RapidAPI; there is always the chance a provider updates the underlying API without updating RapidAPI. So let’s more thoroughly test the PeerReach API before developing our client application.
JSON Schema
This tutorial provides greater attention to the JSON schema than often given to a JSON schema. Unfortunately (in the author’s view), JSON schemas are optional and not required when making your API publicly available. However, a schema can prove invaluable when creating POJOs for serializing JSON in a client application by allowing the objects to be autogenerated from the schema. Organizations using your API can write robust client software to your REST API more easily if you provide a JSON schema.
A JSON schema is a document written in JSON that defines a JSON resource’s structure, content, and semantics. The JSON document is the blueprint that describes the JSON resources that are valid for a given JSON document. If unfamiliar with JSON schemas, refer to one of the following references.
- Understanding JSON Schema
- The JSON Schema website (json-schema.org).
Although this tutorial does not require a detailed knowledge of JSON Schemas, it’s essential you understand JSON schema fundamentals, as the remaining steps are centered around creating and then using a JSON schema to consume the PeerReach API.
Step A – Copy and Clean Schema
After reviewing the API in the RapidAPI dashboard, our first task is copying and cleaning the schema provided by RapidAPI.
- These steps may be obsolete by the time you read this tutorial as RapidAPI is working on a “to clipboard” feature to allow copying the raw JSON schema.
Let’s clean the JSON schema by copying it from the RapidAPI dashboard and then pasting it into a JSON schema validator. We can then use the JSON schema validator to ensure we modify the schema accurately.
- Click the
Example Responses
tab and click on theSchema
tab. - Expand all the schema elements and copy the schema. It is important you first expand all the elements or when you copy the schema to your clipboard it will not copy the hidden text.
- Navigate to JSON Schema Validator (jsonschemavalidator.net) and paste the schema in the
Select schema
text area.
Notice the schema contains the annotations added by RapidAPI. Moreover, it excludes the necessary commas between JSON elements. We must remove these annotations and add the required commas.
- Remove the annotations from the schema.
- Add commas between schema elements.
- Format the schema (click the little box icon in the lower right corner of the
Select schema
text area). - Copy, paste, and save the schema to a file locally on your machine.
- Always treat the example response and schema provided via the dashboard as examples only; test the API and review the results yourself.
After cleaning and saving the schema, we use it to validate JSON responses return from the API endpoint.
Step B – Call API Endpoint and Modify Schema if Needed
The RapidAPI dashboard allows calling and testing a REST API endpoint directly. However, rather than using the RapidAPI dashboard, here we use curl to call the API endpoints. We use curl rather than the dashboard directly because the returned JSON in the dashboard is also annotated and would require clean-up before we could validate the response.
Let’s avoid having to clean-up the JSON response and use curl to call the API from a local command-line terminal. RapidAPI facilitates using curl, thanks to the provided RapidAPI sample code. All we must do is copy and paste the curl commands from the RapidAPI dashboard into our local machine’s terminal window.
- Click the
Code Snippet
tab and select the(Shell) cURL
option on the pulldown menu.
- Click
Copy Code
and open a command-line terminal on your computer.
- Paste the code into the terminal.
- Execute the curl command and obtain a response.
% curl --request GET \ --url 'https://peerreach-peerreach-subscription.p.rapidapi.com/user/lookup.json?screen_name=fredwilson' \ --header 'x-rapidapi-host: peerreach-peerreach-subscription.p.rapidapi.com' \ --header 'x-rapidapi-key: xxxx - snip - xxxx' {"screen_name":"fredwilson","user_id":"1000591","lastupdate":"2020-07-30 13:48:03","followers":"667671","friends":"1328","country":"us","gender":"Male","interests":[],"profiles":["blogger","finance","startups","venture capital","social media","nyc","webtech","business"],"peergroups":[{"topic":"startups","region":"ww","score":"10977","rank":"1"},{"topic":"venture capital","region":"ww","score":"8102","rank":"1"},{"topic":"webtech","region":"ww","score":"20844","rank":"6"},{"topic":"blogger","region":"ww","score":"3450","rank":"67"},{"topic":"finance","region":"ww","score":"4817","rank":"76"}],"subjects":[{"name":"obama","subject_id":"600455","score":"1","assign_date":"2015-02-15 01:01:41"},{"name":"bitcoin","subject_id":"601324","score":"1","assign_date":"2015-01-15 01:01:50"},{"name":"hurricanearthur","subject_id":"1031556","score":"1","assign_date":"2014-07-05 01:01:19"},{"name":"johnoliver","subject_id":"636221","score":"1","assign_date":"2014-06-03 01:05:17"},{"name":"leweb","subject_id":"21775","score":"1","assign_date":"2013-12-11 01:04:01"}]}
- Copy the response JSON and validate it against the schema.
- Fix any errors in the schema.
After pasting the JSON into the Input JSON text area, note that the followers
and friends
elements erroneously specify the element’s format as color
rather than a number
.
- Modify the
color
format tonumber
and the JSON should validate.
- After fixing the schema, call the endpoint using curl with different Twitter users as many times as necessary to feel confident the schema is correct.
Although the JSON validates against the schema, notice that the JSON response contains an array of subjects
not specified by the JSON schema. We should fix this oversight before continuing.
- Modify the schema to include the
subjects
array and the subject’s properties.
Let’s conduct a final test using Kim Kardashian and validate the results using our schema.
- Enter kimkardashian in the RapidAPI dashboard and copy the resultant curl command.
- Execute the command in your command-line terminal.
% curl --request GET \ --url 'https://peerreach-peerreach-subscription.p.rapidapi.com/user/lookup.json?screen_name=kimkardashian' \ --header 'x-rapidapi-host: peerreach-peerreach-subscription.p.rapidapi.com' \ --header 'x-rapidapi-key: 5877ea1b0emshafe96cc3242a9e9p1725f1jsnae263725d505' {"screen_name":"KimKardashian","user_id":"25365536","lastupdate":"2020-08-01 04:08:04","followers":"66093515","friends":"126","country":"","gender":"Female","interests":[],"profiles":["television","arts","fashion","entertainment","family"],"peergroups":[{"topic":"fashion","region":"ww","score":"12355","rank":"1"},{"topic":"arts","region":"ww","score":"5836","rank":"29"},{"topic":"television","region":"ww","score":"5678","rank":"32"},{"topic":"entertainment","region":"ww","score":"6082","rank":"112"}],"subjects":[{"name":"kanye","subject_id":"601379","score":"5","assign_date":"2015-06-29 01:26:05"},{"name":"tbt","subject_id":"601351","score":"3","assign_date":"2015-05-22 01:36:42"},{"name":"christmas","subject_id":"603060","score":"3","assign_date":"2013-12-23 01:32:55"},{"name":"glastonbury","subject_id":"21057","score":"2","assign_date":"2015-06-29 01:26:06"},{"name":"coast","subject_id":"603093","score":"2","assign_date":"2014-02-18 01:44:35"},{"name":"fashion","subject_id":"20835","score":"2","assign_date":"2014-01-06 01:38:30"},{"name":"2015","subject_id":"1034953","score":"1","assign_date":"2015-12-12 01:03:36"},{"name":"canneslions","subject_id":"1010377","score":"1","assign_date":"2015-06-24 01:43:58"},{"name":"vanityfair","subject_id":"963313","score":"1","assign_date":"2015-06-02 01:34:04"},{"name":"letterman","subject_id":"878173","score":"1","assign_date":"2015-05-22 01:36:41"},{"name":"malibu","subject_id":"918427","score":"1","assign_date":"2015-05-02 01:16:19"},{"name":"nepal","subject_id":"22267","score":"1","assign_date":"2015-04-27 01:26:33"},{"name":"grammy","subject_id":"674986","score":"1","assign_date":"2015-02-10 01:10:26"},{"name":"grammys","subject_id":"675010","score":"1","assign_date":"2015-02-10 01:10:26"},{"name":"newyear","subject_id":"671685","score":"1","assign_date":"2015-01-06 01:12:17"},{"name":"cyber","subject_id":"650438","score":"1","assign_date":"2014-12-02 01:15:49"},{"name":"thanksgiving","subject_id":"604076","score":"1","assign_date":"2014-11-25 01:13:02"},{"name":"vma","subject_id":"601919","score":"1","assign_date":"2014-08-25 01:12:11"},{"name":"mothersday","subject_id":"858915","score":"1","assign_date":"2014-05-12 01:34:41"},{"name":"moms","subject_id":"22128","score":"1","assign_date":"2014-05-03 01:39:50"}]}
- Copy the JSON response into the JSON Schema validator and ensure the JSON response is valid.
- After sufficiently confident the schema is correct, save the modified schema locally.
Now that we have tested the endpoint, we can write a client application that consumes the API. We start development by generating Java objects from the schema so we can deserialize the JSON responses into more useful Java object instances. After creating the objects, we then write client software using the UniRest and OkHttp libraries.
Step Three: Code the Client Software
Let’s code the client software that will consume the PeerReach API.
Create Client Objects from Schema
First, we create the Java objects from the JSON schema before writing the UniRest and OkHttp clients. Although there are many available tools to generate these objects, here we use the online tool jsonschema2pojo available at jsonschema2pojo.org.
- Navigate to the jsonschema2pojo website.
- Set the tool properties as,
com.example.twitter.consumer.json.entities
for thePackage
,TwitterUser
as the Class Name,- Java as the Target language,
- JSON Schema as the Source type,
- Jackson 2.x as the Annotation style,
- and check Use double numbers and Include getters and setters.
- Paste the schema into the schema text area.
- Click
Preview
to view the generated POJOs.
- Click
Zip
and then click the zip file to download the POJOs to your local machine. - Create a Java project; here, we are using a SpringBoot application.
- Unzip the classes in your project and modify them to contain a
toString
method.
The following three classes, TwitterUser
, Peergroup
, and Subject
are the classes generated.
package com.example.twitter.consumer.json.entity; import java.util.List; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "screen_name", "user_id", "lastupdate", "followers", "friends", "country", "gender", "interests", "profiles", "peergroups", "subjects" }) public class TwitterUser { @JsonProperty("screen_name") private String screenName; @JsonProperty("user_id") private Long userId; @JsonProperty("lastupdate") private String lastupdate; @JsonProperty("followers") private String followers; @JsonProperty("friends") private String friends; @JsonProperty("country") private String country; @JsonProperty("gender") private String gender; @JsonProperty("interests") private List<Object> interests = null; @JsonProperty("profiles") private List<String> profiles = null; @JsonProperty("peergroups") private List<Peergroup> peergroups = null; @JsonProperty("subjects") private List<Subject> subjects = null; @JsonProperty("screen_name") public String getScreenName() { return screenName; } @JsonProperty("screen_name") public void setScreenName(String screenName) { this.screenName = screenName; } @JsonProperty("user_id") public Long getUserId() { return userId; } @JsonProperty("user_id") public void setUserId(Long userId) { this.userId = userId; } @JsonProperty("lastupdate") public String getLastupdate() { return lastupdate; } @JsonProperty("lastupdate") public void setLastupdate(String lastupdate) { this.lastupdate = lastupdate; } @JsonProperty("followers") public String getFollowers() { return followers; } @JsonProperty("followers") public void setFollowers(String followers) { this.followers = followers; } @JsonProperty("friends") public String getFriends() { return friends; } @JsonProperty("friends") public void setFriends(String friends) { this.friends = friends; } @JsonProperty("country") public String getCountry() { return country; } @JsonProperty("country") public void setCountry(String country) { this.country = country; } @JsonProperty("gender") public String getGender() { return gender; } @JsonProperty("gender") public void setGender(String gender) { this.gender = gender; } @JsonProperty("interests") public List<Object> getInterests() { return interests; } @JsonProperty("interests") public void setInterests(List<Object> interests) { this.interests = interests; } @JsonProperty("profiles") public List<String> getProfiles() { return profiles; } @JsonProperty("profiles") public void setProfiles(List<String> profiles) { this.profiles = profiles; } @JsonProperty("peergroups") public List<Peergroup> getPeergroups() { return peergroups; } @JsonProperty("peergroups") public void setPeergroups(List<Peergroup> peergroups) { this.peergroups = peergroups; } @JsonProperty("subjects") public List<Subject> getSubjects() { return subjects; } @JsonProperty("subjects") public void setSubjects(List<Subject> subjects) { this.subjects = subjects; } public String toString() { ObjectMapper mapper = new ObjectMapper(); try { return mapper.writeValueAsString(this); } catch (JsonProcessingException e) { e.printStackTrace(); return null; } } }
package com.example.twitter.consumer.json.entity; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "name", "subject_id", "score", "assign_date" }) public class Subject { @JsonProperty("name") private String name; @JsonProperty("subject_id") private String subjectId; @JsonProperty("score") private String score; @JsonProperty("assign_date") private String assignDate; @JsonProperty("name") public String getName() { return name; } @JsonProperty("name") public void setName(String name) { this.name = name; } @JsonProperty("subject_id") public String getSubjectId() { return subjectId; } @JsonProperty("subject_id") public void setSubjectId(String subjectId) { this.subjectId = subjectId; } @JsonProperty("score") public String getScore() { return score; } @JsonProperty("score") public void setScore(String score) { this.score = score; } @JsonProperty("assign_date") public String getAssignDate() { return assignDate; } @JsonProperty("assign_date") public void setAssignDate(String assignDate) { this.assignDate = assignDate; } }
package com.example.twitter.consumer.json.entity; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "topic", "region", "score", "rank" }) public class Peergroup { @JsonProperty("topic") private String topic; @JsonProperty("region") private String region; @JsonProperty("score") private Long score; @JsonProperty("rank") private Long rank; @JsonProperty("topic") public String getTopic() { return topic; } @JsonProperty("topic") public void setTopic(String topic) { this.topic = topic; } @JsonProperty("region") public String getRegion() { return region; } @JsonProperty("region") public void setRegion(String region) { this.region = region; } @JsonProperty("score") public Long getScore() { return score; } @JsonProperty("score") public void setScore(Long score) { this.score = score; } @JsonProperty("rank") public Long getRank() { return rank; } @JsonProperty("rank") public void setRank(Long rank) { this.rank = rank; } }
UniRest Client
- Create a new Java client project and add the generated data objects.
- Return to the RapidAPI dashboard, click Code snippets, and select
(Java) Unirest
from the dropdown menu.
- Click
Install SDK
and copy the Maven dependencies to your project’spom.xml
file (assuming you are using Maven).
As we are using Java objects, we must modify the sample code provided by RapidAPI by adding an ObjectMapper
and modifying the HttpResponse
usage to return an Object
rather than a String
.
- Create a class named
UnirestClient
with a method namedgetProfileInformation
. - Place the UniRest initialization code in the
postConstruct
method so that UniRest is initialized immediately after the class is constructed.
package com.example.twitter.consumer.json.client; import java.io.IOException; import javax.annotation.PostConstruct; import org.springframework.stereotype.Component; import com.example.twitter.consumer.TwitterConsumerApplication; import com.example.twitter.consumer.json.entity.TwitterUser; import com.fasterxml.jackson.core.JsonProcessingException; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.UniRest; import com.mashape.unirest.http.exceptions.UniRestException; @Component public class UniRestClient { @PostConstruct private void postConstruct() { UniRest.setObjectMapper(new com.mashape.unirest.http.ObjectMapper() { com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper(); public String writeValue(Object value) { try { return mapper.writeValueAsString(value); } catch (JsonProcessingException e) { e.printStackTrace(); return null; } } public <T> T readValue(String value, Class<T> valueType) { try { return mapper.readValue(value, valueType); } catch (IOException e) { e.printStackTrace(); return null; } } }); UniRest.setDefaultHeader("Accept", "application/json"); } public void getProfileInformation(String userName) { try { HttpResponse<TwitterUser> response = UniRest.get("https://peerreach-peerreach-subscription.p.rapidapi.com/user/lookup.json?screen_name=" + userName) .header(TwitterConsumerApplication.XRAPIDAPIHOST, TwitterConsumerApplication.XRAPIDAPIHOSTVALUE) .header(TwitterConsumerApplication.XRAPIDAPIKEY, TwitterConsumerApplication.XRAPIDAPIKEYVALUE) .asObject(TwitterUser.class); System.out.println(response.getBody().toString()); } catch (UniRestException e) { e.printStackTrace(); } } }
- If using Spring Boot, modify the application class to call the
UniRestClient
.
package com.example.twitter.consumer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.example.twitter.consumer.json.client.UniRestClient; @SpringBootApplication public class TwitterConsumerApplication implements CommandLineRunner { public static String XRAPIDAPIHOST = "x-rapidapi-host"; public static String XRAPIDAPIHOSTVALUE = "peerreach-peerreach-subscription.p.rapidapi.com"; public static String XRAPIDAPIKEY = "x-rapidapi-key"; public static String XRAPIDAPIKEYVALUE = "xxxxxxxxxxxxxxx - snip - xxxxxxxxx"; @Autowired UniRestClient unirestClient; public static void main(String[] args) { SpringApplication.run(TwitterConsumerApplication.class, args); } @Override public void run(String... args) throws Exception { unirestClient.getProfileInformation("elonmusk"); unirestClient.getProfileInformation("fredwilson"); unirestClient.getProfileInformation("kimkardashian"); } }
- Run the application, and you should see the following output.
{"screen_name":"elonmusk","user_id":44196397,"lastupdate":"2020-07-31 04:04:05","followers":"37309513","friends":"98","interests":[],"profiles":["science","webtech","business","astronomy","startups","entrepreneur"],"peergroups":[{"topic":"startups","region":"ww","score":9784,"rank":4},{"topic":"webtech","region":"ww","score":19525,"rank":8},{"topic":"science","region":"ww","score":10348,"rank":13}],"subjects":[{"name":"tesla","subject_id":"600952","score":"3","assign_date":"2015-08-07 01:23:34"},{"name":"dragon","subject_id":"709967","score":"3","assign_date":"2015-04-15 01:46:36"},{"name":"falcon","subject_id":"655592","score":"3","assign_date":"2015-04-15 01:46:33"},{"name":"presidential","subject_id":"646798","score":"1","assign_date":"2016-03-03 01:04:21"},{"name":"hyperloop","subject_id":"601167","score":"1","assign_date":"2015-01-16 01:27:26"},{"name":"rocket","subject_id":"603857","score":"1","assign_date":"2015-01-11 01:15:50"},{"name":"drone","subject_id":"683870","score":"1","assign_date":"2015-01-06 01:15:48"},{"name":"nasa","subject_id":"22231","score":"1","assign_date":"2014-12-06 01:17:42"},{"name":"virgingalactic","subject_id":"1235787","score":"1","assign_date":"2014-11-01 01:16:38"},{"name":"spacex","subject_id":"606286","score":"1","assign_date":"2014-09-17 01:19:51"},{"name":"prince","subject_id":"22658","score":"1","assign_date":"2014-05-26 01:47:34"},{"name":"missouri","subject_id":"22105","score":"1","assign_date":"2014-05-09 02:02:51"},{"name":"ohio","subject_id":"22384","score":"1","assign_date":"2014-02-12 02:04:52"},{"name":"lego","subject_id":"21751","score":"1","assign_date":"2014-02-10 01:51:08"}]} {"screen_name":"fredwilson","user_id":1000591,"lastupdate":"2020-07-30 13:48:03","followers":"667671","friends":"1328","country":"us","gender":"Male","interests":[],"profiles":["blogger","finance","startups","venture capital","social media","nyc","webtech","business"],"peergroups":[{"topic":"startups","region":"ww","score":10977,"rank":1},{"topic":"venture capital","region":"ww","score":8102,"rank":1},{"topic":"webtech","region":"ww","score":20844,"rank":6},{"topic":"blogger","region":"ww","score":3450,"rank":67},{"topic":"finance","region":"ww","score":4817,"rank":76}],"subjects":[{"name":"obama","subject_id":"600455","score":"1","assign_date":"2015-02-15 01:01:41"},{"name":"bitcoin","subject_id":"601324","score":"1","assign_date":"2015-01-15 01:01:50"},{"name":"hurricanearthur","subject_id":"1031556","score":"1","assign_date":"2014-07-05 01:01:19"},{"name":"johnoliver","subject_id":"636221","score":"1","assign_date":"2014-06-03 01:05:17"},{"name":"leweb","subject_id":"21775","score":"1","assign_date":"2013-12-11 01:04:01"}]} {"screen_name":"KimKardashian","user_id":25365536,"lastupdate":"2020-08-01 04:08:04","followers":"66093515","friends":"126","country":"","gender":"Female","interests":[],"profiles":["television","arts","fashion","entertainment","family"],"peergroups":[{"topic":"fashion","region":"ww","score":12355,"rank":1},{"topic":"arts","region":"ww","score":5836,"rank":29},{"topic":"television","region":"ww","score":5678,"rank":32},{"topic":"entertainment","region":"ww","score":6082,"rank":112}],"subjects":[{"name":"kanye","subject_id":"601379","score":"5","assign_date":"2015-06-29 01:26:05"},{"name":"tbt","subject_id":"601351","score":"3","assign_date":"2015-05-22 01:36:42"},{"name":"christmas","subject_id":"603060","score":"3","assign_date":"2013-12-23 01:32:55"},{"name":"glastonbury","subject_id":"21057","score":"2","assign_date":"2015-06-29 01:26:06"},{"name":"coast","subject_id":"603093","score":"2","assign_date":"2014-02-18 01:44:35"},{"name":"fashion","subject_id":"20835","score":"2","assign_date":"2014-01-06 01:38:30"},{"name":"2015","subject_id":"1034953","score":"1","assign_date":"2015-12-12 01:03:36"},{"name":"canneslions","subject_id":"1010377","score":"1","assign_date":"2015-06-24 01:43:58"},{"name":"vanityfair","subject_id":"963313","score":"1","assign_date":"2015-06-02 01:34:04"},{"name":"letterman","subject_id":"878173","score":"1","assign_date":"2015-05-22 01:36:41"},{"name":"malibu","subject_id":"918427","score":"1","assign_date":"2015-05-02 01:16:19"},{"name":"nepal","subject_id":"22267","score":"1","assign_date":"2015-04-27 01:26:33"},{"name":"grammy","subject_id":"674986","score":"1","assign_date":"2015-02-10 01:10:26"},{"name":"grammys","subject_id":"675010","score":"1","assign_date":"2015-02-10 01:10:26"},{"name":"newyear","subject_id":"671685","score":"1","assign_date":"2015-01-06 01:12:17"},{"name":"cyber","subject_id":"650438","score":"1","assign_date":"2014-12-02 01:15:49"},{"name":"thanksgiving","subject_id":"604076","score":"1","assign_date":"2014-11-25 01:13:02"},{"name":"vma","subject_id":"601919","score":"1","assign_date":"2014-08-25 01:12:11"},{"name":"mothersday","subject_id":"858915","score":"1","assign_date":"2014-05-12 01:34:41"},{"name":"moms","subject_id":"22128","score":"1","assign_date":"2014-05-03 01:39:50"}]}
- Note we are using the provided version of UniRest Java on RapidAPI (version 1.4.9). For an example using the latest UniRest library, refer to this tutorial on RapidAPI UniRest version Java Documentation.
OkHttp Client
- Select
Java (OkHttp)
and click theInstall SDK
link. - Copy the
Creating a Request
code and past in thegetProfileInformation
method.
- Modify the
pom.xml
file to reflect the OkHttp dependency.
<dependency> <groupId>com.squareup.okhttp</groupId> <artifactId>okhttp</artifactId> <version>2.7.5</version> </dependency>
- Modify the
getProfileInformation
method to create anObjectMapper
. - Load the response into the
ObjectMapper
and deserialize into aTwitterUser
.
package com.example.twitter.consumer.json.client; import java.io.IOException; import org.springframework.stereotype.Component; import com.example.twitter.consumer.TwitterConsumerApplication; import com.example.twitter.consumer.json.entity.TwitterUser; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; @Component public class OkHttpTwitterClient { public void getProfileInformation(String userName) { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("https://peerreach-peerreach-subscription.p.rapidapi.com/user/lookup.json?screen_name=" + userName) .get().addHeader(TwitterConsumerApplication.XRAPIDAPIHOST, TwitterConsumerApplication.XRAPIDAPIHOSTVALUE) .addHeader(TwitterConsumerApplication.XRAPIDAPIKEY, TwitterConsumerApplication.XRAPIDAPIKEYVALUE).build(); try { Response response = client.newCall(request).execute(); ObjectMapper objectMapper = new ObjectMapper(); TwitterUser user = objectMapper.readValue(response.body().string(), TwitterUser.class); System.out.println(user.toString()); } catch (IOException e) { e.printStackTrace(); } } }
- Modify
TwitterConsumerApplication
to call theOkHttpTwitterClient
.
package com.example.twitter.consumer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.example.twitter.consumer.json.client.OkHttpTwitterClient; import com.example.twitter.consumer.json.client.UniRestClient; @SpringBootApplication public class TwitterConsumerApplication implements CommandLineRunner { public static String XRAPIDAPIHOST = "x-rapidapi-host"; public static String XRAPIDAPIHOSTVALUE = "peerreach-peerreach-subscription.p.rapidapi.com"; public static String XRAPIDAPIKEY = "x-rapidapi-key"; public static String XRAPIDAPIKEYVALUE = "xxxx -snip- xxxx"; @Autowired UniRestClient unirestClient; @Autowired OkHttpTwitterClient okHttpTwitterClient; public static void main(String[] args) { SpringApplication.run(TwitterConsumerApplication.class, args); } @Override public void run(String... args) throws Exception { //unirestClient.getProfileInformation("elonmusk"); //unirestClient.getProfileInformation("fredwilson"); okHttpTwitterClient.getProfileInformation("elonmusk"); okHttpTwitterClient.getProfileInformation("fredwilson"); } }
- Run the application, and you should see the following output.
{"screen_name":"elonmusk","user_id":44196397,"lastupdate":"2020-07-31 04:04:05","followers":"37309513","friends":"98","interests":[],"profiles":["science","webtech","business","astronomy","startups","entrepreneur"],"peergroups":[{"topic":"startups","region":"ww","score":9784,"rank":4},{"topic":"webtech","region":"ww","score":19525,"rank":8},{"topic":"science","region":"ww","score":10348,"rank":13}],"subjects":[{"name":"tesla","subject_id":"600952","score":"3","assign_date":"2015-08-07 01:23:34"},{"name":"dragon","subject_id":"709967","score":"3","assign_date":"2015-04-15 01:46:36"},{"name":"falcon","subject_id":"655592","score":"3","assign_date":"2015-04-15 01:46:33"},{"name":"presidential","subject_id":"646798","score":"1","assign_date":"2016-03-03 01:04:21"},{"name":"hyperloop","subject_id":"601167","score":"1","assign_date":"2015-01-16 01:27:26"},{"name":"rocket","subject_id":"603857","score":"1","assign_date":"2015-01-11 01:15:50"},{"name":"drone","subject_id":"683870","score":"1","assign_date":"2015-01-06 01:15:48"},{"name":"nasa","subject_id":"22231","score":"1","assign_date":"2014-12-06 01:17:42"},{"name":"virgingalactic","subject_id":"1235787","score":"1","assign_date":"2014-11-01 01:16:38"},{"name":"spacex","subject_id":"606286","score":"1","assign_date":"2014-09-17 01:19:51"},{"name":"prince","subject_id":"22658","score":"1","assign_date":"2014-05-26 01:47:34"},{"name":"missouri","subject_id":"22105","score":"1","assign_date":"2014-05-09 02:02:51"},{"name":"ohio","subject_id":"22384","score":"1","assign_date":"2014-02-12 02:04:52"},{"name":"lego","subject_id":"21751","score":"1","assign_date":"2014-02-10 01:51:08"}]} {"screen_name":"fredwilson","user_id":1000591,"lastupdate":"2020-07-30 13:48:03","followers":"667671","friends":"1328","country":"us","gender":"Male","interests":[],"profiles":["blogger","finance","startups","venture capital","social media","nyc","webtech","business"],"peergroups":[{"topic":"startups","region":"ww","score":10977,"rank":1},{"topic":"venture capital","region":"ww","score":8102,"rank":1},{"topic":"webtech","region":"ww","score":20844,"rank":6},{"topic":"blogger","region":"ww","score":3450,"rank":67},{"topic":"finance","region":"ww","score":4817,"rank":76}],"subjects":[{"name":"obama","subject_id":"600455","score":"1","assign_date":"2015-02-15 01:01:41"},{"name":"bitcoin","subject_id":"601324","score":"1","assign_date":"2015-01-15 01:01:50"},{"name":"hurricanearthur","subject_id":"1031556","score":"1","assign_date":"2014-07-05 01:01:19"},{"name":"johnoliver","subject_id":"636221","score":"1","assign_date":"2014-06-03 01:05:17"},{"name":"leweb","subject_id":"21775","score":"1","assign_date":"2013-12-11 01:04:01"}]}
Final Project
After creating both clients, if using Spring Boot, our pom.xml
file appears as follows.
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.2.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>TwitterConsumer</artifactId> <version>0.0.1-SNAPSHOT</version> <name>TwitterConsumer</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!-- RapidAPI SDK Install Maven Dependencies --> <dependency> <groupId>com.mashape.unirest</groupId> <artifactId>unirest-java</artifactId> <version>1.4.9</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3.6</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpasyncclient</artifactId> <version>4.0.2</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.3.6</version> </dependency> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20140107</version> </dependency> <!-- End RapidAPI SDK Install Maven Dependencies --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.4</version> </dependency> <dependency> <groupId>com.squareup.okhttp</groupId> <artifactId>okhttp</artifactId> <version>2.7.5</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
Step Four: Test the Client Software
After developing the software, you should test the software. Notice that we already tested the PeerReach API rather thoroughly before developing the client software. Concentrate testing efforts on the client software developed and its integration with the PeerReach API. Producing tests for the client software is beyond this tutorial’s scope. For more information on testing, refer to the article API Testing: Testing APIs with RapidAPI for Teams, also on the RapidAPI blog.
Conclusion
In this tutorial, we used the UniRest and OkHttp libraries to write a Java client to the PeerReach Twitter API on RapidAPI. We used the RapidAPI dashboard combined with a JSON schema validation tool to test and modify PeerReach’s JSON schema. We then used the schema to create POJOs for deserializing the JSON into Java objects usable by our client application. The PeerReach API is a valuable tool for obtaining detailed information on a person’s Twitter profile. The steps in this tutorial will help you use the PeerReach API on RapidAPI more robustly, and will save you considerable rework if you invest the upfront time to test the API and generate a JSON schema before writing client software to the API.
Leave a Reply