How to create a custom API connector in Ruby
In the How to use the httparty Ruby gem section, we walked through the httparty
Ruby gem segment and we discussed how to integrate built-in classes from the gem to call an API. If you need something more specific, it's a good idea to create a separate class to manage the API processes. That's what we are going to do here while still leveraging some of the key modules supplied by HTTParty
:
require 'rubygems' require 'httparty' class StackExchange include HTTParty base_uri 'api.stackexchange.com' end
In this code, we created a class called StackExchange
. As the first step, we included the HTTParty
module so that this class can access the methods provided by the gem. Next, we set base_uri
, which is the Stack Exchange API URI's path.
Since this is a custom class, let's create an initializer that takes in the arguments service
and page
. Inside of the initialize
method, we will store our API query inside of the @options
instance variable. Then...