In this post, we'll see how to make API calls in Ruby on Rails, focusing on practical examples and simple steps that are beginner-friendly.

I’ll also cover the different libraries and methods you can use for API calls in Rails.

In Ruby on Rails, an API call is a request made to an external service to retrieve or send data. For example, you might call a weather API to fetch weather information, or a payment gateway API to process payments.

Making an API call involves sending an HTTP request (GET, POST, PUT, DELETE) to a URL and receiving a response. You can then use this data in your Rails application, like displaying information on a webpage or storing it in a database.

How to Make an API Call in Ruby on Rails

Let’s go through the basic steps to make an API call in a Ruby on Rails application.

Step 1: Install Required Gem

To start making API calls, you can use the HTTParty gem, which makes it easy to work with HTTP requests. You can also use RestClient or Rails' built-in Net::HTTP, but HTTParty is simple and widely used.

To install HTTParty, add it to your Gemfile:

ruby
gem 'httparty'

Then run:

bash
bundle install

Step 2: Making a Simple GET Request

After installing the gem, you can make a simple GET request to fetch data from an API. Here's an example of how to fetch JSON data from an API:

ruby
# app/controllers/weather_controller.rb
class WeatherController < ApplicationController
  def show
    response = HTTParty.get("https://api.openweathermap.org/data/2.5/weather?q=London&appid=your_api_key")
    @weather_data = response.parsed_response
  end
end

for example:

  • We make a GET request to the OpenWeather API to fetch the current weather data for London.
  • The parsed_response method converts the JSON response into a Ruby hash for easy access.

Step 3: Handling the Response

Once you make the API call, you’ll likely get a JSON response. To handle this response:

  • You can check the status code to ensure the request was successful.
  • You can parse the JSON response and use the data in your application.

Here’s an example that checks the status code and handles errors:

ruby
# app/controllers/weather_controller.rb
class WeatherController < ApplicationController
  def show
    response = HTTParty.get("https://api.openweathermap.org/data/2.5/weather?q=London&appid=your_api_key")

    if response.success?
      @weather_data = response.parsed_response
    else
      @error_message = "Error fetching weather data"
    end
  end
end

If the API call is successful, the weather data is parsed into a Ruby hash and stored in @weather_data. If not, an error message is displayed.

Making a POST Request in Ruby on Rails

In addition to GET requests, you might need to make a POST request to send data to an API. For example, you might need to send user data to a third-party service or submit a form.

Here’s an example of a POST request using HTTParty:

ruby
# app/controllers/payment_controller.rb
class PaymentController < ApplicationController
  def create
    body = {
      amount: 100,
      currency: "USD",
      description: "Payment for product"
    }

    response = HTTParty.post("https://paymentgateway.com/api/v1/charge", body: body.to_json, headers: { 'Content-Type' => 'application/json' })

    if response.success?
      @payment_status = response.parsed_response
    else
      @payment_error = "Payment failed"
    end
  end
end

for instance:

  • We send a POST request with payment data (amount, currency, description) to a payment gateway.
  • The request body is converted into JSON using to_json.
  • The Content-Type header specifies that we’re sending JSON data.

How Ruby on Rails Works
How to Host Rails Apps for Free

When making API calls in Rails, it's important to handle errors properly by showing clear messages if something goes wrong, like a failed request or server issue. If an API call takes time, use background jobs to keep the app responsive, so users don't have to wait. To avoid making repeated requests, cache the API data if it doesn’t change often, which speeds up your app and reduces server load. Lastly, always keep your API keys secure by storing them in environment variables instead of hard-coding them into your code, protecting your sensitive information.

Example of Storing API Keys Securely

In your terminal, set the environment variable:

bash
export API_KEY="your_api_key_here"

In your Rails application:

ruby
api_key = ENV['API_KEY']

This way, your API keys are not exposed in the codebase.

Making API calls in Ruby on Rails is a common task when building modern web applications. Whether you're fetching data, submitting forms, or interacting with third-party services, learning how to make API requests is an essential skill.


Comments(0)