# Step 1: Install the HTTParty gem
# Add the following line to your Gemfile and run 'bundle install'
gem 'httparty'
# Step 2: Require the HTTParty module in your Ruby script
require 'httparty'
# Step 3: Define a class that includes the HTTParty module
class MyHttpClient
include HTTParty
# Step 4: Set the base URI for the API you want to interact with
base_uri 'https://api.example.com'
# Step 5: Define HTTParty options such as headers, query parameters, etc.
headers 'Content-Type' => 'application/json'
# Step 6: Define methods for different HTTP methods (GET, POST, etc.)
def self.get_example(resource_path, query_params = {})
get(resource_path, query: query_params)
end
def self.post_example(resource_path, body_params = {})
post(resource_path, body: body_params.to_json)
end
# Additional Step: Handling response
def self.handle_response(response)
if response.success?
puts 'Request was successful!'
puts "Response Code: #{response.code}"
puts "Response Body: #{response.body}"
else
puts 'Request failed!'
puts "Response Code: #{response.code}"
puts "Response Body: #{response.body}"
end
end
end
# Step 7: Make HTTP requests using the defined methods
response_get = MyHttpClient.get_example('/example/resource', { param1: 'value1', param2: 'value2' })
MyHttpClient.handle_response(response_get)
response_post = MyHttpClient.post_example('/example/resource', { key1: 'value1', key2: 'value2' })
MyHttpClient.handle_response(response_post)