Skip to main content
March 23, 2026Noble Desktop Publishing Team/9 min read

Web Services: Integrating a Third-Party API

Master Third-Party API Integration with Ruby on Rails

Tutorial Prerequisites

This tutorial assumes completion of exercises 8A-11A. If you haven't completed them, follow the setup instructions to clone the repository and check out the correct branch.

Topics Covered in This Ruby on Rails Tutorial:

Installing the HTTParty Gem and Integrating Real-Time Bitcoin Pricing into Order Summaries

Learning Objectives

HTTParty Integration

Learn to install and configure the HTTParty gem for making external API calls in Rails applications.

Bitcoin API Implementation

Integrate real-time Bitcoin exchange rates from BitPay API to display dynamic pricing in your e-commerce site.

AJAX Updates

Implement dynamic Bitcoin total updates using AJAX to provide seamless user experience without page refreshes.

Exercise Overview

Modern web applications rarely exist in isolation—they thrive through strategic integration with third-party services and APIs. In this exercise, we'll explore web services from both perspectives: first, we'll integrate a live Bitcoin pricing API into our e-commerce platform, and in the next exercise, we'll learn to expose our own data for partner consumption. This dual approach will give you the complete toolkit for building interconnected, data-rich applications that leverage the broader web ecosystem.

  1. If you completed the previous exercises, you can skip the following sidebar. We strongly recommend finishing exercises 8A–11A before starting this one, as they establish the foundational cart and order functionality we'll be extending. If you haven't completed them, follow the setup instructions below.

    Web Services Integration Approach

    Current Exercise

    Consume Third-Party API

    Integrate external web service (Bitcoin rates) into your Rails application

    Next Exercise

    Syndicate Your Data

    Learn to expose your application data to external partners

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.

Repository Setup Process

1

Navigate and Prepare

Open Terminal, navigate to Class Files folder, and remove existing nutty directory

2

Clone and Configure

Clone the Noble Desktop nutty repository and checkout branch 11A

3

Install Dependencies

Run bundle and yarn install to set up all required gems and JavaScript dependencies

Getting Bitcoin Quotes with HTTParty

Cryptocurrency payment integration has become increasingly important for e-commerce platforms, especially as digital currencies gain mainstream adoption. We're going to enhance our site to support both traditional dollar payments and Bitcoin transactions. Since Bitcoin's exchange rate is notoriously volatile—often fluctuating significantly within hours—we need real-time pricing data to ensure accurate conversions.

For this integration, we'll use BitPay's robust API at bitpay.com/api/rates, which provides reliable, up-to-date exchange rates across multiple currencies. To interact with this external service efficiently within our Rails application, we'll leverage the HTTParty gem—a powerful, lightweight HTTP client that simplifies API consumption with an intuitive Ruby interface.

  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). Having the entire project structure visible will help you navigate between files more efficiently.

  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 to get your development environment properly configured.

    Why Bitcoin Integration?

    Bitcoin's volatile exchange rate requires real-time API integration. The BitPay API at bitpay.com/api/rates provides reliable, free access to current exchange rates across 165 currencies.

    API Response Data

    165
    currencies supported by BitPay API

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.
  • In your code editor, open nutty > Gemfile.

  • Scroll to the bottom and add the HTTParty gem dependency:

    # Use HTTParty to make remote API calls
    gem 'httparty'

    HTTParty is one of the most popular Ruby gems for HTTP requests, offering a clean, readable syntax that makes API integration straightforward. It handles JSON parsing automatically and provides helpful methods for common HTTP operations.

  • Save the file, then close it.

  • Switch to Terminal to install the new dependency.

  • Install the new gem by typing:

    bundle

    Bundler will download and install HTTParty along with any of its dependencies, ensuring version compatibility with your existing gems.

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

  • Start up the server again by typing:

    rails s

    Restarting the server ensures that the new gem is properly loaded into your application's runtime environment. This is a crucial step that many developers forget, leading to frustrating "uninitialized constant" errors.

  • Now let's explore HTTParty's capabilities using the Rails console—an invaluable tool for testing API interactions before implementing them in your application code. Switch back to the bash tab in Terminal and start the Rails console:

    rails c
  • 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 comprehensive response—an array of hashes containing Bitcoin exchange rates for currencies worldwide. This real-time data is exactly what we need for accurate payment processing.

  • Let's examine the response structure. Type the following:

    response.count

    Terminal will return approximately 165, representing the number of currencies currently supported by BitPay's API. This extensive coverage makes the service suitable for global e-commerce applications.

  • Type the following to inspect the data format:

    response.first

    This shows us the structure of individual currency entries, helping us understand how to extract the specific data we need.

  • For better readability when working with complex data structures, type:

    pp response
  • Scroll up to see that this gives us a much cleaner, formatted response, making it easier to analyze the returned data structure.

    pp is short for "Pretty Print"—a essential debugging tool that formats complex variables for human readability. You'll find yourself using this frequently when working with API responses and complex data structures.

  • Now let's extract the specific data we need. We need to find the U.S. dollar equivalent. Type the following command to search using its currency code:

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

    This Ruby enumerable method efficiently searches through the array to locate the USD entry, returning all associated data for that currency.

  • To get just the exchange rate value, we can chain methods together—one of Ruby's most powerful features:

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

    Perfect! This single line gives us the current Bitcoin-to-USD exchange rate, which is all we need for our payment integration. This demonstrates the elegance of API integration: calling the service with HTTParty, then parsing and utilizing the response. The implementation possibilities from here are limitless.

  • HTTParty Installation Process

    1

    Add Gem to Gemfile

    Add 'gem httparty' to your Gemfile with appropriate comment

    2

    Install and Restart

    Run bundle install, stop the server with Ctrl-C, then restart with rails s

    3

    Test in Console

    Use Rails console to test HTTParty.get calls and explore the API response structure

    Rails Console Testing

    Use 'pp response' for pretty printing complex API responses. The find method with code comparison helps locate specific currency data from the returned array of hashes.

    Adding the Total in Bitcoin

    Now that we understand how to fetch Bitcoin exchange rates, let's integrate this functionality into our application architecture. We'll add the Bitcoin conversion logic to our shared methods module, ensuring it can be reused across both cart and order objects—a key principle of maintainable Rails development.

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

      NOTE: Remember that earlier we extracted common functionality between cart and order objects into this shared module. This architectural decision now pays dividends as we can add Bitcoin support to both objects with a single implementation.

    2. Add the following method after the existing total method:

      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 Ruby's greatest strengths is its expressiveness—allowing complex operations to be written concisely. The bitcoin_rate line could have been expanded into five separate lines, but method chaining lets us accomplish the entire API call, search, and data extraction in a single, readable statement.

    3. Now we need to calculate and return the Bitcoin equivalent price. Add the conversion logic:

      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 use 1.0 rather than 1 to ensure floating-point arithmetic and preserve decimal precision. Bitcoin amounts are conventionally expressed to eight decimal places (the smallest unit being a "satoshi"), so we round accordingly for proper display and calculation accuracy.

    4. With our Bitcoin calculation logic complete, let's integrate it into the user interface. Save the file and move on to updating the cart display.

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

    6. Locate the total display section around lines 69–72 and copy this code:

      <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 modify the new code to display the Bitcoin total:

      <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 remove the number_to_currency helper from the Bitcoin row, as we're displaying the raw Bitcoin amount with the "BTC" suffix.

    8. Save the file and prepare to test the initial implementation.

    9. Open a browser and navigate to: localhost:,000

    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. Excellent! You should now see in the Order Summary that alongside the regular Total, there's a new Total in Bitcoin row showing the real-time cryptocurrency equivalent. However, we need to ensure this functionality works seamlessly with our AJAX-powered cart updates.

    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 to handle Bitcoin total updates.

    15. Edit the duplicated code to update the Bitcoin display:

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

      NOTE: Remember to remove number_to_currency from the Bitcoin line. Notice the naming convention: we use hyphens for HTML IDs and CSS classes, but underscores for Ruby method names—following Rails conventions ensures consistency across your application.

      This architecture demonstrates the power of Rails' MVC pattern: our business logic resides in the model (the shared module), keeping our views clean and our calculations centralized. No code duplication, no scattered API calls—just clean, maintainable architecture.

    16. Save the file and test the complete AJAX integration.

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

    18. Change the quantity of an item in your cart to test the dynamic updates.

    19. Click the update link. Both the dollar total and the Total in Bitcoin should update seamlessly in real-time, demonstrating a fully integrated cryptocurrency payment display system!

    20. Clean up your Rails console session by switching back to Terminal and typing:

      exit
    21. Leave Terminal, your code editor, and browser open as we will continue building upon this foundation in the following exercise, where we'll explore the flip side of API integration: exposing your own data for external consumption.

    Method Chaining Efficiency

    Ruby's method chaining allows complex operations in single lines. The bitcoin_rate calculation chains HTTParty.get, find, and hash access together for concise, readable code.

    Implementation Steps

    0/4
    View Consistency

    Remember to update both the static HTML view and the AJAX update view. Use dashes for CSS IDs and underscores for Ruby method names following Rails conventions.

    Key Takeaways

    1HTTParty gem simplifies external API integration in Rails applications with minimal configuration required
    2The BitPay API provides real-time Bitcoin exchange rates for 165 currencies through a free, reliable service
    3Rails console testing allows developers to explore API responses interactively before implementing production code
    4Method chaining in Ruby enables complex API operations to be written concisely in single lines of code
    5Shared methods in modules ensure DRY principles when functionality is needed across multiple models like carts and orders
    6AJAX implementation requires updating both static HTML views and JavaScript response templates for consistent user experience
    7Bitcoin calculations require 8 decimal place precision and careful handling of float division using 1.0 instead of integer 1
    8Rails conventions dictate using dashes for CSS selectors and underscores for Ruby method names to maintain code consistency

    RELATED ARTICLES