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.
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:
- Have Ruby installed on your system.
- Use a library like
net/http(built into Ruby) orHTTParty/Faradayfor more advanced features.
Request​
Ruby’s standard library includes net/http, which can be used to make HTTP requests.
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​
- API Endpoint: The
URIclass parses the URL. - Request Data: The
datahash contains the data to send. Theto_jsonmethod converts it to JSON format. - Http Request: The
Net::HTTPandNet::HTTP::Postclasses create and send the HTTP request. - Headers: The
Content-Typeheader specifies that the body contains JSON. - Response Handling: The
http.requestmethod sends the request, and the response is printed. - Error Handling: The
rescueblock 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:
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
rescueto manage exceptions.Timeouts: Configure timeouts in
Net::HTTP:http.read_timeout = 10Reusable Functions: Wrap HTTP logic in reusable methods for cleaner code.
With these basics, you can confidently use Ruby to interact with APIs!