Twitter is a popular social media platform. Anyone can get a free account, post updates on it, and follow accounts to see the latest updates of the people, topics, and news they’re interested in.
In this blog post, we’ll look at how to use the Twitter API in combination with data from PeerReach.com. Specifically we will use this API:
If you’d like a refresher on any of the terms or concepts used in this article, check out these articles:
- What is an API?
- What is an API Call?
- What is an API Request?
- What is an API Endpoint?
- How To Use an API with JavaScript
Try out the PeerReach Twitter API
Using the PeerReach Twitter API will give us useful context and information about popular Twitter users, such as knowing how influential they may be within their domain of expertise.
Step 1: Visit to the API endpoint’s page
Visit the endpoint for this API.
Step 2: Fill out the required parameter
This API uses a Twitter handle. We’re going to use this API to analyze John Resig‘s account, creator of the popular jQuery library. So let’s fill that in at the bottom of this page:
Step 3: Test the Endpoint API
Click the “Test Endpoint” button. It will automatically subscribe you to this endpoint for this test, hassle-free.
Note: if you don’t have a RapidAPI.com account, make sure to sign up for a free account before doing this step.
Step 4: Explore the API results
In order to know how to use the API, we need to know what kind of data it gives us.
We see that it’s a basic JSON object. What’s interesting here is the list of profiles, peergroups, and subjects.
Using the Twitter API from JavaScript
Now that we know how this Twitter API works, we can start getting PeerReach data from JavaScript.
Step 1: Open the Code Snippets tab and select JavaScript
Step 2: Select the fetch JavaScript code snippet
Step 3: Paste this into your DevTools console
Make sure you’re using a modern browser like Google Chrome or the new Microsoft Edge, and open your Developer Tools with F12.
Before we paste it, we’ll need to clean up the code a little bit, because the fetch()
function call returns a Promise, which isn’t useful to us. Fortunately, Chrome and Edge DevTools both support top-level await. So let’s transform our fetch call to use await/async syntax:
const response = await fetch("https://peerreach.p.rapidapi.com/user/lookup.json?screen_name=jeresig", { "method": "GET", "headers": { "x-rapidapi-host": "peerreach.p.rapidapi.com", "x-rapidapi-key": "YOUR_RAPID_API_KEY_GOES_HERE" } }); const body = await response.json();
Step 4: Explore the API results
Type body
to view the result of the variable we just assigned in the last step, and you should see something like this:
Great, this is exactly what we saw in the RapidAPI page when we tested the endpoint! Now we can get started on writing some code to show this in a nicer view.
Example: Building a Social Profiling app in React with Twitter API
We’re going to build a dashboard that highlights the interesting aspects of a person’s social profile:
- Profiles: Categories that the account fits into
- Peer Groups: How does the account compare to peer accounts?
- Subjects: What subjects does the account tweet about?
This is what it will look like when we’re done:
Step 1: Setup a React app using Create React App
React is quickly becoming one of the easiest ways to create a dashboard like the one we’re going to build, because it automatically updates what the user sees (the “view”) based on the data we give it. Since we’re primarily working with data results from APIs, React is a great fit.
For this tutorial, we’re not going to look at our usage of React in much detail. Instead, we’ll just focus on how we’re using the Twitter API from within Javascript inside React. If you’d like to get more familiar with React, be sure to check out:
- The official website: Reactjs.org
- How To Use an API with ReactJS
- How to Fetch Data from an API with React Hooks
So let’s set up our sample React app:
- Install NPM if it’s not already installed.
- Get a good IDE or editor, like VS Code.
- Run
npx create-react-app twitter-rapidapi
- Follow the instructions and run
npm start
- The app will automatically open localhost:3000 in your browser.
Step 2: Replace the default React component with our own
Replace the contents of the src/App.js
file with this:
import React from 'react'; import './App.css'; function App() { const [name, setName] = React.useState('jeresig'); const [profile, setProfile] = React.useState(null); const check = async () => { const response = await fetch("https://peerreach.p.rapidapi.com/user/lookup.json?screen_name=" + name, { "method": "GET", "headers": { "x-rapidapi-host": "peerreach.p.rapidapi.com", "x-rapidapi-key": YOUR_RAPID_API_KEY_GOES_HERE } }); const body = await response.json(); console.log(body); setProfile(body); }; return ( <div className="app"> <section> <h2>Username</h2> <span> @ <input autoFocus value={name} onChange={e => setName(e.target.value)} /> </span> <button onClick={check}>Check</button> </section> {profile && <> <section> <h2>Profiles</h2> <ul> {profile.profiles?.map(name => ( <li key={name}>{name}</li> ))} </ul> </section> <section> <h2>Peer Groups</h2> <table> <thead> <tr> <th>Rank</th> <th>Group</th> </tr> </thead> <tbody> {profile.peergroups?.map(group => ( <tr key={group.topic}> <td>#{group.rank}</td> <td>{group.topic}</td> </tr> ))} </tbody> </table> </section> <section> <h2>Subjects</h2> <table> <thead> <tr> <th>Subject</th> <th>Assigned</th> <th>Score</th> </tr> </thead> <tbody> {profile.subjects?.map(subject => ( <tr key={subject.name}> <td>{subject.name}</td> <td>{subject.assign_date.split('-')[0]}</td> <td>{subject.score}</td> </tr> ))} </tbody> </table> </section> </>} </div> ); } export default App;
Now the app should look like this in your browser:
The code is very simple: Given the profile
variable, render an HTML <table>
element for each section of interest. When the “Check” button is clicked, we call the async function defined on line 8, which fetches the data from our Twitter API, and inserts the new data into the profile
variable, showing a new table.
Step 3: Style our app component with CSS
As professional software developers, we always like our apps to look nice, no matter what size they are. Thanks to CSS Grids, we can do that here with very little effort.
So let’s add the following CSS to the src/App.css
file:
html, body { background: #f7f7f7; } .app { display: inline-grid; gap: 1em; margin: 2em; grid-template-areas: "a d" "b d" "c d"; } .app section:nth-child(4) { grid-area: d; } .app section { display: grid; gap: 1em; align-content: baseline; padding: 1em; background: #fff; box-shadow: 0px 2px 6px 2px #0002; } .app ul, .app h2 { margin: 0; } .app th { padding-bottom: 0.5em; text-align: left; } .app td { padding-right: 1em; } .app button { background: #17f; color: #fff; font: inherit; border: none; border-radius: 3px; outline: none; padding: 0.5em 1.5em; } .app button:active { background-color: #05b; } .app input { border: 1px solid #999; border-radius: 3px; font: inherit; padding: 0.5em; outline: none; } .app input:focus { outline: auto #17f; }
Now the app should look like this:
Step 4: Try our brand new JavaScript Twitter API example app!
Now let’s try it out! Click “Check” and you should see this:
Give it a try with other Twitter accounts you might follow. Here are a few suggestions:
- @dhh: Creator of Ruby on Rails
- @codinghorror: Co-founder of StackOverflow.com
- @BrendanEich: Creator of JavaScript
Conclusion
Using the Twitter API is very simple using RapidAPI. Just make the API call in your language of choice, get the data out of the API response, and use it however you’d like. In this tutorial, we just rendered it into a table, but you can also use it for data analytics, data aggregation, or anything else.
Other APIs of interest
Here are some other APIs you may be interested in:
- Twilio SMS API: Use SMS capabilities from an API.
- Imgur API: Interact with the popular image hosting site via its API.
- SendGrid API: Deliver emails with this API.
- WordsAPI: An API to get detailed data about English words.
Leave a Reply