Skip to main content
Noble Desktop Publishing Team/7 min read

Web Services: Integrating a Third-Party API

What This Tutorial Covers

HTTP Clients

HTTParty and Faraday for REST calls.

Auth Tokens

Securely store and use API credentials.

Error Handling

Handle timeouts, rate limits, and bad responses.

Build Web Development Skills at Noble Desktop

Noble Desktop's Full-Stack Web Development Certificate teaches modern web development concepts that transfer across Ruby, Python, and JavaScript stacks.

Dive into this comprehensive tutorial on integrating third-party web services into your Ruby on Rails site, specifically focusing on incorporating real-time Bitcoin price quotes into your application.

Topics Covered in This Ruby on Rails Tutorial:

Installing the HTTParty Gem, Adding Bitcoin Total to the Order Summary

Exercise Overview

Let’s approach web services from two ends. First, in this exercise, we’ll look at how to integrate a third-party web service into our site. In the next exercise, we’ll learn how we can syndicate our data out to a partner.

  1. If you completed the previous exercises, you can skip the following sidebar. We recommend you finish the previous exercises (8A–11A) before starting this one. If you haven’t finished them, do the following sidebar.

    If You Did Not Do the Previous Exercises (8A–11A)

    1. Close any files you may have open.
    2. Open the Finder and navigate to Class Files > yourname-Rails Class
    3. Open Terminal.
    4. Type cd and a single space (do NOT press Return yet).
    5. Drag the yourname-Rails Class folder from the Finder to the Terminal window and press ENTER.
    6. Run rm -rf nutty to delete your copy of the nutty site.
    7. Run Git clone https://bitbucket.org/Noble Desktop/nutty.Git to copy the That Nutty Guy Git repository.
    8. Type cd nutty to enter the new directory.
    9. Type Git checkout 11A to bring the site up to the end of the previous exercise.
    10. Run bundle to install any necessary gems.
    11. Run yarn install—check-files to install JavaScript dependencies.

Getting Bitcoin Quotes with HTTParty

We’re going to set up our site so that users can pay with either dollars or bitcoin. The exchange rate of Bitcoin is pretty volatile and its value relative to the dollar fluctuates all the time. Fortunately there are lots of free APIs out there; one of the best is at bitpay.com/api/rates

We’re going to need a good tool for interacting with it in our Rails application.

  1. For this exercise we’ll continue working with the nutty folder located in Desktop > Class Files > yourname-Rails Class > nutty

    If you haven’t already done so, we suggest opening the nutty folder in your code editor if it allows you to (like Sublime Text does).

  2. You should still have a window with two tabs open in Terminal from the last exercise, the first of which is running the server. If you don’t, complete the following sidebar.

    Restarting the Rails Server

    1. In Terminal, cd into the nutty folder:
    • Type cd and a space.
    • Drag the nutty folder from Desktop > Class Files > yourname-Rails Class onto the Terminal window (so it will type out the path for you).
    • In Terminal, hit Return to change directory.
    1. In Terminal, type the following:

      rails s
    2. Open a new tab (Cmd–T) leaving our server running in the old tab.
    3. In the new tab, cd into the nutty folder:
    • Type cd and a space.
    • Drag the nutty folder from Desktop > Class Files > yourname-Rails Class onto the Terminal window (so it will type out the path for you).
    • In Terminal, hit Return to change directory.
  3. In your code editor, open nutty > Gemfile.

  4. Scroll to the bottom and add:

    # Use HTTParty to make remote API calls
    gem 'httparty'
  5. Save the file, then close it.

  6. Switch to Terminal.

  7. Install the new gem by typing:

    bundle
  8. Switch to the tab running the server and hit CTRL–C to shut it down.

  9. Start up the server again by typing:

    rails s

    This is actually a good opportunity to use the Rails console a bit and get a feel for what HTTParty does and how it returns responses to you.

  10. Switch back to the bash tab in Terminal and start the Rails console:

    rails c
  11. Type the following, making sure to write HTTParty as written (it is case-sensitive):

    response = HTTParty.get('https://bitpay.com/api/rates')

    You will get a long response, an array of hashes, which shows the Bitcoin exchange rate in various countries.

  12. Type the following:

    response.count

    Terminal will return 165, the number of currencies that were just returned.

  13. Type the following:

    response.first

    This just gives us the first returned entry.

  14. Type the following:

    pp response
  15. Scroll up to see that this gives us a cleaner response, making it much easier to see the data that’s been returned.

    pp is short for “Pretty Print”. This command makes it possible to inspect large & complex variables.

  16. We need to find the U.S. dollar equivalent. Type the following command to search using its code:

    response.find { |r| r['code'] == 'USD' }

    That gives us back all the U.S. dollar info, but what if we really wanted to pare down so we only see the U.S. dollar rate?

  17. We can do that by typing:

    response.find { |r| r['code'] == 'USD' }['rate']

    Great, that’s all the info we’ll need to incorporate into our application to show customers a real-time price quote in Bitcoin. That’s basically all there is to integrating a third-party service: calling out to it using HTTParty, then parsing and using the response. The rest is up to your imagination!

Adding the Total in Bitcoin

The code that we just wrote is going to go into our shared_method module so that it can be reused by both carts and orders.

  1. In your code editor, open nutty > lib > checkout_shared_methods.rb

    NOTE: Remember that earlier we broke out methods that are shared between cart and order objects into this file.

  2. Add the following three lines of code shown in bold:

    def total
          subtotal
       end
    
       def bitcoin_total
          bitcoin_rate = HTTParty.get('https://bitpay.com/api/rates').find { |r| r['code'] == 'USD'}['rate']
       end
    end

    One of the great things about Ruby is that you can be very concise with it. The bitcoin_rate line could have been five lines of code, but instead we are able to write it all in one line by chaining methods together.

  3. Now we need to return the price in Bitcoin. Add:

    def bitcoin_total
       bitcoin_rate = HTTParty.get('https://bitpay.com/api/rates').detect { |r| r['code'] == 'USD'}['rate']
       (total * (1.0 / bitcoin_rate)).round(8)
    end

    NOTE: We put 1.0 rather than 1 so that it will return decimals. Bitcoin balances are often written out to eight decimal places, so we set it to round to 8.

  4. That should be all we need to get the Bitcoin total for any given object, so let’s move on to adding the Bitcoin total to the cart screen. Save the file.

  5. In your code editor, open nutty > app > views > cart > index.html.erb

  6. Copy the code around lines 69–72:

    <tr class="total-price">
       <td>Total</td>
       <td id="total"><%= number_to_currency @cart.total %></td>
    </tr>
  7. Paste directly below the copied lines, then edit the new code as shown in bold:

    <tr class="total-price">
       <td>Total</td>
       <td id="total"><%= number_to_currency @cart.total %></td>
    </tr>
    <tr class="total-price">
       <td>Total in Bitcoin</td>
       <td id="bitcoin- total"><%= @cart.bitcoin_total %> BTC</td>
    </tr>

    NOTE: Don’t forget to delete the second instance of number_to_currency.

  8. Save the file.

  9. Open a browser and navigate to: localhost:3000

  10. Click on a product then click the Add To Cart button.

  11. Sign in if prompted. If you did not create an account in a previous exercise, click the Sign up link, enter an email and password, then click Sign Up.

  12. You should see in the Order Summary that in addition to the regular Total, there is now Total in Bitcoin.

    We need to get this working with our AJAX as well.

  13. In your code editor, open nutty > app > views > line_items > update.js.erb

  14. Copy the last line and paste it directly below the original.

  15. Edit the code as shown in bold:

    $('td#total').html('<%= number_to_currency @cart.total %>');
    $('td#bitcoin- total').html('<%= @cart.bitcoin_ total %> BTC');

    NOTE: Don’t forget to delete number_to_currency in the new line.

    The convention is to use a dash for the class and an underscore for the method.

    Isn’t it great that we can put our logic in the model, rather than having to duplicate the whole Bitcoin calculation or API call?

  16. Save the file.

  17. Go to the browser and reload the cart page: localhost:3000/cart

  18. Change the Quantity of an item in your cart.

  19. Click the update link. The Total in Bitcoin should update in the Order Summary!

  20. Switch back to Terminal and type the following to exit the Rails console.

    exit
  21. Leave Terminal, your code editor, and browser open as we will continue to work with them in the following exercise.