Search code examples
rubyapihttp-postget-request

Spark Api GET/POST request data using Ruby


How do I write a script that retrieves a listing by ID and saves it to a file as JSON: http://sparkplatform.com/docs/api_services/listings

How do I write a script that creates a new contact record, and then prints the new contact’s record (standard output is fine): http://sparkplatform.com/docs/api_services/contacts

SPARK_API Gem github page to answer the questions: https://github.com/sparkapi/spark_api (provides auto parser)

CODE

SparkApi.client.get  "/listings/#{listing_id}", :_expand => "CustomFields"
SparkApi.client.post "/listings/#{listing_id}/contacts

I'm newer to Ruby, how would I use the GET/POST requests properly?


Solution

  • Do the following:

    1. Install ruby
    2. Run gem install spark_api
    3. Create a SPARK_API_KEY and SPARK_API_SECRET

    Then, you basically need to run a get and a post request.

    This is the script from the documentation:

    require 'spark_api'
    SparkApi.configure do |config|
      config.endpoint   = 'https://sparkapi.com'
      # Using Spark API Authentication, refer to the Authentication documentation for OAuth2
      config.api_key    = 'SPARK_API_KEY'
      config.api_secret = 'SPARK_API_SECRET'
    end
    
    listing_id = 12345
    filename = 'my_file.json'
    
    def get_listing(listing_id, filename)
      response = SparkApi.client.get "/listings/#{listing_id}", :_expand => "CustomFields"
      save_to_file(response, filename)
    end
    
    def create_contact(listing_id)
      SparkApi.client.post "/listings/#{listing_id}/contacts"
    end
    
    def save_to_file(response, filename)
      File.open(filename, 'w') do |f|
        f << response.body
      end
    end
    

    Use your own HTTP client like faraday or httparty but use the Gem which wraps all the API logic.