Skip to main content

Ruby

Ruby is a dynamic, object-oriented language known for its simplicity and readability. It is often used for web development and scripting. It has a strong developer community and elegant syntax.

tip

Ruby on Rails, a popular framework, simplifies API development with built-in conventions and tools. Ruby’s readable syntax and robust libraries make it a great choice for API consumption and creation.

Let's make a POST request to a hypothetical API endpoint, https://api.example.com/resource, to send JSON data using Ruby.

Prerequisites​

Before making API calls with Ruby, ensure you:

  1. Have Ruby installed on your system.
  2. Use a library like net/http (built into Ruby) or HTTParty/Faraday for more advanced features.

Request​

Ruby’s standard library includes net/http, which can be used to make HTTP requests.

Example
require 'net/http'
require 'json'

# Define the API endpoint
url = URI("https://api.example.com/resource")

# Create the data to send in the POST request
data = {
name: "John Doe",
email: "johndoe@example.com",
age: 30
}

# Convert the data to JSON
json_data = data.to_json

# Create the HTTP request
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request['Content-Type'] = 'application/json'
request.body = json_data

# Send the request and get the response
begin
response = http.request(request)
puts "Response Code: #{response.code}"
puts "Response Body: #{response.body}"
rescue StandardError => e
puts "An error occurred: #{e.message}"
end

How it works​

  1. API Endpoint: The URI class parses the URL.
  2. Request Data: The data hash contains the data to send. The to_json method converts it to JSON format.
  3. Http Request: The Net::HTTP and Net::HTTP::Post classes create and send the HTTP request.
  4. Headers: The Content-Type header specifies that the body contains JSON.
  5. Response Handling: The http.request method sends the request, and the response is printed.
  6. Error Handling: The rescue block catches and displays any errors.

Response​

If the API successfully processes the request, it might return a JSON response like:

{
"status": "success",
"message": "Data received successfully",
"id": "12345"
}

This response will be printed by the puts statement.

Adding authentication​

If the API requires authentication, include it in the request:

  • Basic Authentication:

    request.basic_auth('username', 'password')
  • Bearer Token:

    request['Authorization'] = "Bearer YOUR_TOKEN_HERE"

Using HTTParty​

HTTParty is a popular Ruby gem for making HTTP requests. Here’s the same example using HTTParty:

Example
require 'httparty'

url = 'https://api.example.com/resource'

response = HTTParty.post(url, {
body: {
name: "John Doe",
email: "johndoe@example.com",
age: 30
}.to_json,
headers: {
'Content-Type' => 'application/json'
}
})

puts "Response Code: #{response.code}"
puts "Response Body: #{response.body}"

Saving the response​

To save the API’s response to a file:

File.write('response.json', response.body)

Tips for using Ruby with APIs​

  • Error Handling: Use libraries like rescue to manage exceptions.

  • Timeouts: Configure timeouts in Net::HTTP:

    http.read_timeout = 10
  • Reusable Functions: Wrap HTTP logic in reusable methods for cleaner code.

With these basics, you can confidently use Ruby to interact with APIs!