An official website of the United States government
Accessing the Public Data API with Ruby / Ruby on RailsOn This Page:Before Processing:If you are using Ruby or Ruby On Rails to connect to the BLS Public Data API, you can use the rest-client ruby gem. All Ruby code should start with the following line of code: require 'rest_client' Calling the BLS Public Data APIUsing the RestClient POST method, you can access the API using the following code. You must specify JSON in the content_type, since the Public Data API only accepts and returns JSON data. API Version 2.0require 'rest_client' require 'json' url = 'https://api.bls.gov/publicAPI/v2/timeseries/data/' response = RestClient.post(url, {'seriesid => ['seriesid'], 'startyear' => '1995', 'endyear' => '1998' }.to_json, :content_type => 'application/json') API Version 1.0require 'rest_client' require 'json' url = 'https://api.bls.gov/publicAPI/v1/timeseries/data/' response = RestClient.post(url, {'seriesid => ['seriesid'], 'startyear' => '1995', 'endyear' => '1998' }.to_json, :content_type => 'application/json') Post Processing:Once the data has been retrieved from the Public Data API, you can use a JSON parser to further consume and inspect the response. We have provided examples of three JSON parsers for your convenience. JSON Implementation for RubyYou can install the Ruby gem library with the following command: gem install json Once you have installed the Ruby gem library, you can use JSON using the following command: require 'json' Once you have installed and required JSON, you can parse it using the following: response = RestClient.post(url,.... parsed_json = JSON(response) ActiveSupport's Built-in JSON Processorresponse = RestClient.post(url,.... parsed_json = ActiveSupport::JSON.decode(response.body) Ruby Response Built-in JSON Processor// Get Response response = RestClient.post(url,....) // Call to_json on response client to get JSON response my_json = response.to_json
Last Modified Date: October 16, 2014 |