View all our code samples

Using HttpParty in Ruby

HTTParty is a Ruby HTTP client library that provides a simple and intuitive API for making HTTP requests and handling responses. It abstracts away the complexities of HTTP communication and provides features like automatic parsing of JSON and XML responses, request timeouts, and response caching.

We've implemented a code sample that you can re-use to convert your HTML documents to PDF, JPG, PNG or WEBP using PDFShift and Ruby:

require 'httparty'
require 'json'

def convert(api_key, params, endpoint = 'pdf')
  # Ensure the endpoint is valid
  unless %w[pdf png jpg webp].include?(endpoint)
    raise ArgumentError, 'Invalid endpoint specified'

  # Set the API URL
  url = "{endpoint}"

  # Set headers
  headers = {
    'Content-Type' => 'application/json',
    'Authorization' => "Basic #{Base64.strict_encode64("api:#{api_key}")}"

  # Make the POST request
  response =, body: params.to_json, headers: headers)

  # Check for successful response
  unless response.success?
    raise "Request failed with status code #{response.code}: #{response.body}"

  # Return the response based on the presence of filename or webhook
  response_body.key?('filename') || response_body.key?('webhook') ? JSON.parse(response.body) : response.body

Here's how you can use the above code:

  result = convert('sk_XXXXXXXXXXXXXX', {'source' => ''})
  puts result
rescue StandardError => e
  puts "Error: #{e.message}"

We've tested this code with the latest version of HttpParty and it's ready to be used in your project.

But if you were to encounter any bugs or issues while running it (or if you want to suggest changes to improve the code), please contact us and we'll be happy to help you out.