Web Services: Integrating a Third-Party API

Free Ruby on Rails Tutorial

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.

This exercise is excerpted from Noble Desktop’s past web development training materials. Noble Desktop now teaches JavaScript and the MERN Stack in our Full Stack Development Certificate. To learn current skills in web development, check out our coding bootcamps in NYC and live online.

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

Full-Stack Web Development Certificate: Live & Hands-on, In NYC or Online, 0% Financing, 1-on-1 Mentoring, Free Retake, Job Prep. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

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.

Noble Desktop Publishing Team

The Noble Desktop Publishing Team includes writers, editors, instructors, and industry experts who collaborate to publish up-to-date content on today's top skills and software. From career guides to software tutorials to introductory video courses, Noble aims to produce relevant learning resources for people interested in coding, design, data, marketing, and other in-demand professions.

More articles by Noble Desktop Publishing Team

How to Learn Coding

Master coding with hands-on training. Learning how to code in JavaScript, Python, and other popular languages can pave the way to a job in tech, such as web development, data science & analytics, or software engineering.

Yelp Facebook LinkedIn YouTube Twitter Instagram