Internet search has gone way beyond the traditional web search. Thanks to other mediums of content shared over multiple online platforms, there is a new dimension to search. Influencer search is one such option. It is a smart strategy that helps in content marketing. It lets you find authority content written by influencers, and also gives you a way to build an engagement with them through social media.
When it comes to looking up influencers, a web search engine sucks. Social Animal provides some great APIs to make this job easier for you. In this blog post, we take you through a tutorial on building a demo web app for influencer search using the Social Animal Influencer Search API with Ruby on Rails.
So let’s get started. At first, we take you through a tour of the API. Subsequently, you will follow a step-by-step tutorial to build the demo app.
Getting started with Influencer Search API
The Influencer Search API is available as part of RapidAPI’s API marketplace. Follow the steps below to sign up for RapidAPI and access this API.
1. Sign up for RapidAPI Account
To begin using the Influencer Search API, you’ll first need to sign up for a free RapidAPI developer account. With this account, you get a universal API Key to access all APIs hosted in RapidAPI.
RapidAPI is the world’s largest API marketplace, with over 10,000 APIs and a community of over 1,000,000 developers. Our goal is to help developers find and connect to APIs to help them build amazing apps.
2. Subscribe to Influencer Search API
Once signed in, log in to your RapidAPI account. You can directly access the Influencer Search API console.
Inside the API console, click on the “Pricing” tab at the top to see the available subscriptions for this API. You can choose the basic subscription. It gives you limited access to the API, with ten free API calls per month.
3. Test the API Endpoint
Toggle back to the “Endpoints” tab on the API console. You can see the endpoints listed on the left column and the API parameters on the middle column.
Note that this API has only one endpoint, “POST InfluencersAPI” to trigger the Influencer search. You can hit the blue “Test Endpoint” button to trigger the API with the default keyword “digital marketing.”
If all goes well, you should see the API response in the right column of the API console.
The API returns a JSON response containing an array of profile information for each influencer. Blowing up the first element in the array gives you a closer look at the individual influencer.
{ "id":947957610 "id_str":"947957610" "name":"Jorge Montano" "screen_name":"BossJMontano" "description":"Soy el rey del mame ~ Marketing digital ~ Compongo, produzco, dirijo, hago estrategia, soy lider de opinión, soy Mexicano y solo me falta un oscar." "location":"México" "time_zone":NULL "followers_count":1352901 "statuses_count":2750 "account_created_at":"2012/11/14 03:33:53" "lang":"es" "profile_image_url":"http://pbs.twimg.com/profile_images/908525376468586496/8nZ0j8r6_normal.jpg" "url":NULL "verified":false "default_profile":false "favourites_count":4284 "listed_count":1217 "utc_offset":NULL "profile_use_background_image":false "default_profile_image":false "profile_image_url_https":"https://pbs.twimg.com/profile_images/908525376468586496/8nZ0j8r6_normal.jpg" "friends_count":1569 "created_at":"2019/02/06 11:56:23" "updated_at":"2020/09/10 02:07:46" "category":"general" "protected":false }
Now that you see the API response, it means that your API subscription is working. We are all set to leverage this API to build a web app for influencer search.
How to use the Influencer Search API with Ruby on Rails
Let us put this API to some use by building a web app. Using Ruby on Rails, the powerful web framework for the Ruby programming language, you can use this API for making a demo web application for influencer search. In this section, we take you through a tutorial to build this app by writing the code, step by step.
Before writing the code, you have to perform a few steps for configuring your development environment.
Prerequisites
For this tutorial, you need the following tools and libraries installed on your development machine.
1. rbenv or RVM: This is the Ruby version management tool. Install it from this link.
2. Ruby (2.7.1): Install the Ruby programming language environment from the official link.
3. Bundler: Bundler is a dependency management system for Ruby.
gem install bundler |
4. Node.js: Install the Node.js platform from the official website.
5. Yarn: Install the Yarn package manager from the official link.
6. Ruby on Rails (6.0.3.3): Finally, install the Ruby on Rails framework.
gem install rails -v 6.0.3.3 |
Now you are all set to code the web app. Open a terminal and fire up your favorite code editor. Follow the below step to building this app.
Step 1: Create Your Rails App
It’s a good idea to start with a top-level directory for your project. Create a project directory and make sure that your terminal’s current directory is set to that path.
Run the following command on the terminal to create a new Rails project. Let’s call it “influencer”.
rails new influencer –skip-test –skip-active-record |
Note that we are not using a database or tests to keep things simple. In the world outside this demo, tests come first. You may also want to use a database to persist data.
The rails command will create a directory named influencer. This directory contains the skeleton of your app.
Now cd into the directory.
cd influencer |
Rails ships with Puma, a simple but fast server. Time to fire up the server.
rails server |
Puma runs on port 3000 by default. Open your browser and go to localhost:3000. If you did everything right, you should see a cheery greeting from Rails.
Step 2: Setting Up Bootstrap
Rails 6 ships with webpacker. Webpacker is a gem wrapping webpack. It is a tool used to bundle JavaScript files and manage project assets such as images, CSS, and HTML. It is desirable to use webpacker with Rails 6 even though the asset pipeline is still available. In this demo, we will use webpacker.
First, install Bootstrap, jquery, and popper.js by typing the following in your terminal.
yarn add bootstrap jquery popper.js |
After yarn completes installing, open ‘config/webpack/environment.js’. The default environment.js file looks as shown below.
const { environment } = require('@rails/webpacker') module.exports = environment
You have to include Bootstrap, JQuery, and popper.js as plugins. Paste the following code after the first line.
const webpack = require("webpack") environment.plugins.append("Provide", new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', Popper: ['popper.js', 'default'] }));
Your ‘config/webpack/environment.js’ file should now look like;
const { environment } = require('@rails/webpacker') const webpack = require("webpack") environment.plugins.append("Provide", new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', Popper: ['popper.js', 'default'] })); module.exports = environment
The next step is to include Bootstrap in the project. Create a subdirectory called stylesheets inside the path app/javascript. Now create a file named ‘application.scss’ inside app/javascript/stylesheets subdirectory. Open the file and add the following.
@import "~bootstrap/scss/bootstrap"
Now open the file ‘app/javascript/packs/application.js’ and add the following two lines at the end of the file.
import "bootstrap" import "../stylesheets/application.scss"
The file now looks like:
require("@rails/ujs").start() require("turbolinks").start() require("channels") import "bootstrap" import "../stylesheets/application.scss"
Finally, open ‘app/views/application.html.erb’ and add the following line inside the <head> tag after the stylesheet_link_tag.
<%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
With this, you have successfully integrated Bootstrap in the project.
Step 3: Configuring Routes
Open the file ‘config/routes.rb’ and add the following routes inside the block.
root to: 'search#new' post '/search', to: 'search#index'
Your ‘config/routes.rb’ file now looks like:
Rails.application.routes.draw do root to: 'search#new' post '/search', to: 'search#index' end
The first line maps the root (localhost:3000) to the search controller’s new action. The second line maps http POST to the search controller’s index action.
After defining the routes, it’s time to create the search controller and views.
Step 4: Creating the Search Controller
Type the following in your terminal to create the search controller.
rails new controller search |
The command creates the controller file ‘app/controllers/search_controller.rb’. Open the file and add the new and the index actions. The result should look as shown below.
class SearchController < ApplicationController def new end def index end end
The skeleton of the controller is ready.
The controller has two methods, new and index. You don’t have to add anything to the new method. We will revisit the index method later. But for now, let’s create the form that the user will fill for searching influencers.
Step 5: Creating the Search Form
Create a file named ‘new.html.erb’ inside app/views/search subdirectory. The code for the form is:
<div class="container"> <div class="row mt-4"> <div class="col-12"> <h1 class="text-center">Search Social Media Influencers</h1> <p class="text-center">Enter a keyword in the field below</p> <%= form_tag '/search' do %> <div class="form-group"> <%= text_field_tag :query, nil, {class: "form-control"} %> </div> <%= submit_tag "Find Influencers", {class: "btn btn-primary", id: "search", role: "status"} %> <div id="button"> </div> <% end %> </div> </div> </div>
This code is a simple Bootstrap form that will POST to /search, sending the query submitted by the user as :query parameter, which can be accessed in the controller via parameters[:query].
Let’s move on to the most exciting part of the app, the API call.
Step 6: API Call
Before writing the code for calling the API, let’s decide where it will reside?
You can put the code inside the index method, below all the search form posts to index method. But doing so will violate the single responsibility principle. It is more logical to put the code for calling the API inside its own class. Let’s call this class ApiCall and create it by editing ‘app/services/api_call.rb.’
class ApiCall require 'uri' require 'net/http' attr_reader :query def initialize(query) @query = query end def call http.request(request) end private def url URI("https://influencer-search.p.rapidapi.com/api/v1/influencer/search") end def request_body "{ \"query\": { \"keyword\": \"#{query}\" }}" end def request request = Net::HTTP::Post.new(url) request["x-rapidapi-host"] = 'influencer-search.p.rapidapi.com' request["x-rapidapi-key"] = '<YOUR_RAPIDAPI_KEY>' request["content-type"] = 'application/json' request["accept"] = 'application/json' request.body = request_body request end def http http = Net::HTTP.new(url.host, url.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE http end end
It may seem like a lot is going on here, but this class is pretty simple. There is one public method named call and a bunch of configuration methods. Let’s explore them one by one.
The initialize method takes the query and passes it to the instance variable @query. The attr_reader declaration encapsulates @query instance variable inside query method.
The url method creates a URI for the Social Animal API endpoint. The request_body method simply returns the properly formatted request that will be sent to the API. The request method builds the request payload. Finally, the http method creates a http request object.
The call method is where everything comes together. This method sends a HTTP request to Influencer API with the request payload. The API responds with some HTTP headers and an HTTP body.
Before saving this file, make sure to replace the placeholder <YOUR_RAPIDAPI_KEY> inside the request method with your actual RapidAPI subscription key.
Step 7: Calling the API and Accepting the Request
For this step, we have to move back to the search controller. We will modify the index action, as shown below.
Open ‘app/controllers/search_controller.rb’ and modify the index method.
def index response = ApiCall.new(params[:query]).call.read_body @results = ActiveSupport::JSON.decode(response) @results[:query] = params[:query] end
The first line creates an ApiCall object, sends it the call message, and then reads the HTTP response body. The body of the HTTP response is a JSON payload. However, it is received as a string. The second line takes this string, converts it into a JSON object, and assigns it to the instance variable @result.
The last line appends the query to the @result variable. The reason for doing this will become clear shortly.
Step 8: Creating the Result Page
Let’s create the result page for displaying the response from Social Animal Influencer Search API by editing ‘app/views/search/index.html.erb’.
<div class="container"> <div class="row mt-4"> <div class="col-12"> <h1 class="text-center mb-4">Top <%= influencer_count %> <%= query %> Influencers</h1> <table class="table"> <thead> <tr class="text-center"> <th scope="col">Name</th> <th scope="col">Description</th> <th scope="col">Followers</th> <th scope="col">Handle</th> </tr> </thead> <tbody> <% influencers.each do |influencer| %> <tr> <td class="text-center"> <%= image_tag influencer["profile_image_url"], class: "img-thumbnail" %><br/> <%= influencer["name"] %><br/> <span class="text-muted"><%= influencer["location"] %></span> </td> <td class="text-center"> <%= influencer["description"] %> </td> <td class="text-center"><%= number_with_delimiter(influencer["followers_count"]) %></td> <td class="text-center"> <%= link_to("@#{influencer['screen_name']}", "https://www.twitter.com/#{influencer['screen_name']}",{target: :blank}) %> </td> </tr> <% end %> </tbody> </table> </div> </div> </div>
This view code may look longish, but most of it is vanilla HTML that displays the result in a tabular format like this:
The table has the following columns.
- The first column displays the image, name and location
- The second column shows the description
- The third column is for the count of followers
- The final column displays the Twitter handle of the influencer. The twitter handle is linked to the influencer’s twitter profile page and clicking on it will open the profile page in a new window.
Let’s create influencers, query, and influencer_count methods called in ‘app/views/search/index.html.erb’. These are helper methods, and the best place to put them is the SearchHelper module. Add them to the file ‘app/helpers/search_helper.rb.’
module SearchHelper def influencers @results["data"] end def query @results[:query].titlecase end def influencer_count @results["data"].count end end
Step 9: Polishing it Off
Let’s end this tutorial by adding a spinner to the “Find Influencers” button.
It is straightforward to add a spinner using Bootstrap. Add the following lines of code to ‘app/views/search/new.html.erb’ after the submit_tag.
<div id="button"> </div>
This <div> element is used to insert the code for the spinner dynamically.
Create a file named ‘app/javascript/packs/spinner.js’ and add the following code.
function loadSpinner() { var submit = document.getElementById('search'); submit.hidden = true; var div = document.getElementById('button'); var button = '<button class="btn btn-primary" type="button" disabled>\n\ <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>\n\ Searching...\n\ </button>'; div.innerHTML += button; } window.onload = function() { document.getElementById('search').onclick = loadSpinner; }
Upon clicking the “Find Influencers,” this code triggers two actions:
- It hides the “Find Influencers” button.
- Add the code for spinner inside the <div> with id of button.
Let’s include this JavaScript within view. Open ‘app/views/search/new.html.erb’ and add the line below at the top of the page.
<%= javascript_pack_tag 'spinner.js' %>
That’s it. The web app is now ready!
Step 10: Launch the app
Launch the app by typing the following command on the terminal.
rails server |
By default, the app is launched at port 3000.
Open the app on the browser at localhost:3000, and you are all set to explore the top influencers in any field.
Your Turn to Spruce Up the Influencer Search App
The Social Animal Influencer API returns a lot more data for each influencer. Some of the valuable data include timezone, creation date, and verified status. These fields are easy to add by styling the result table of the app. We leave it as an exercise for you to enhance the description column of each row of results by adding these bits of information below the description text.
You can also check out the other APIs offered by Social Animal to power your social media campaigns.
April says
Hi, thanks for the nice tutorial! Any ideas as to why I’m getting a parse error in the search_controller: JSON::ParserError (767: unexpected token at ”) in the line below?
@results = ActiveSupport::JSON.decode(response)
April says
This code is full of bugs.
Shyam Purkayastha says
This error seems to indicate that your API quota is over. Please ensure that you haven’t exhausted your limits.
You can also check RoR debug console to check for that.
April says
Thanks for your reply! I was actually using a different API where the quota is no question. I did change the code like this, though:
response = ApiCall.new(params[:query]).call.read_body
@results = ActiveSupport::JSON.decode(response)
This worked perfectly.