Web Services: Integrating a Third-Party API
Master Third-Party API Integration with Ruby on Rails
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.
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.
Repository Setup Process
Navigate and Prepare
Open Terminal, navigate to Class Files folder, and remove existing nutty directory
Clone and Configure
Clone the Noble Desktop nutty repository and checkout branch 11A
Install Dependencies
Run bundle and yarn install to set up all required gems and JavaScript dependencies
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 cType 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 responseScroll 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
Add Gem to Gemfile
Add 'gem httparty' to your Gemfile with appropriate comment
Install and Restart
Run bundle install, stop the server with Ctrl-C, then restart with rails s
Test in Console
Use Rails console to test HTTParty.get calls and explore the API response structure
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.
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
Ensures the method is available to both cart and order objects
Forces decimal precision in Ruby calculations
Matches standard Bitcoin precision formatting
Ensures Bitcoin totals update dynamically and on page load
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