Parsing the response using REST vs. SOAP API in Ruby - ruby

I am trying to parse a response that I receive using Rest API calls, but get an error when I say, something like: response.body.first[1]. I am transferring Soap API calls to rest API calls. Is response.first something that can only be used in Soap, if so what is the equivalent in Rest? Here is the code snippet that I am having trouble with:
url = ##rest_base_url.to_s + "filters/#{id.to_s}/results"
resource = RestClient::Resource.new url, #username, #password
response = resource.get
data = JSON.parse(response.body)["data"]
if response.body.first[1][:return].nil?
requirements = nil
elsif response.body.first[1][:return].is_a?(Array)
# puts "|get_requirements| req is an array".blue
requirements = []
Thank you

Related

Healthcare API (Ruby client) returning null

I'm trying to fetch a Patient from the FHIR store via the Ruby client and it always returns null.
I am successful when querying via CURL. Here is the CURL command I'm running (full path redacted):
curl -X GET \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
"https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID/fhir/Patient/PATIENT_ID"
This returns the proper FHIR Patient resource.
My Ruby code looks like:
require 'google/apis/healthcare_v1'
require 'googleauth'
service = Google::Apis::HealthcareV1::CloudHealthcareService.new
scope = 'https://www.googleapis.com/auth/cloud-platform'
service.authorization = Google::Auth::ServiceAccountCredentials.make_creds(
json_key_io: File.open('REDACTED'),
scope: scope
)
service.authorization.fetch_access_token!
project_id = REDACTED
location = REDACTED
dataset_id = REDACTED
fhir_store_id = REDACTED
resource_type = 'Patient'
patient_id = REDACTED
name = "projects/#{project_id}/locations/#{location}/datasets/#{dataset_id}/fhirStores/#{fhir_store_id}/fhir/Patient/#{patient_id}"
response = service.read_project_location_dataset_fhir_store_fhir(name)
puts response.to_json
I'm not getting any authentication errors. The CURL example returns the appropriate result, while the Ruby client example returns null.
Any ideas?
The Ruby library automatically tries to parse the response as JSON. Since the responses from the Healthcare API (or any FHIR server) is Content-Type: application/fhir+json, this isn't recognized by the Ruby library, and it just returns nil for the parsed response.
I got this to work by using the skip_deserialization option for the API call (docs), so instead you should try
require 'json'
name = "projects/#{project_id}/locations/#{location}/datasets/#{dataset_id}/fhirStores/#{fhir_store_id}/fhir/Patient/#{patient_id}"
response = service.read_project_location_dataset_fhir_store_fhir(name, options: {
skip_deserialization: true,
})
patient = JSON.parse(response)
You would actually have to parse the response yourself anyways, because the Ruby response type for these calls is Google::Apis::HealthcareV1::HttpBody, which is essentially just a wrapper around a raw JSON object.

AWS Lambda Chalice: "The request could not be satisfied" Error

I want my lambda function to return the response of another lambda function invoked via AWS API Gateway.
Both functions are deployed by Lambda Chalice to different APIs.
When the first function sends a request to the 2nd functions API endpoint, I am getting an error response saying that "The request could not be satisfied".
Any help is appreciated.
Edit to include some code as requested; shortened for brevity:
#app.route('/verify_user_token', methods=['GET'], cors=True)
def verify_user_token():
request = app.current_request
params = request.query_params or {}
# do your things here; if all goes well:
r = requests.get(ANOTHER_AWS_API_GATEWAY_ENDPOINT_URL, data=params)
return r.text

Is their a way to create Dummy Response with 500 code in HTTParty

Here my HTTParty code
response = HTTParty.post(api_url,body: form_data,timeout: 5)
rescue Timeout::Error
## create dummy response with 500 error code
response = HTTParty::Response.new()
ensure
response
all I'm trying to do is ensure If the HTTParty is unable to connect the given website create a dummy response body objec
But when I try to create a dummy Response object like this
## response = HTTParty::Response.new(Rack::Request.new(api_url),Rack::Response.new('TimeOut Error',500),'TimeOutError')
but this does not work because my response object does not respond_to to_hash
Can anyone suggest a better way to accomplish the same
In case anybody comes looking after 4 years, one could try the following:
httparty_req = HTTParty::Request.new Net::HTTP::Get, '/'
nethttp_resp = Net::HTTPInternalServerError.new('1.1', 500, 'Internal Server Error')
response = HTTParty::Response.new(httparty_req, nethttp_resp, lambda {''}, body: '')

Reading Withings API ruby

I have been trying for days to pull down activity data from the Withings API using the OAuth Ruby gem. Regardless of what method I try I consistently get back a 503 error response (not enough params) even though I copied the example URI from the documentation, having of course swapped out the userid. Has anybody had any luck with this in the past. I hope it is just something stupid I am doing.
class Withings
API_KEY = 'REMOVED'
API_SECRET = 'REMOVED'
CONFIGURATION = { site: 'https://oauth.withings.com', request_token_path: '/account/request_token',
access_token_path: '/account/access_token', authorize_path: '/account/authorize' }
before do
#consumer = OAuth::Consumer.new API_KEY, API_SECRET, CONFIGURATION
#base_url ||= "#{request.env['rack.url_scheme']}://#{request.env['HTTP_HOST']}#{request.env['SCRIPT_NAME']}"
end
get '/' do
#request_token = #consumer.get_request_token oauth_callback: "#{#base_url}/access_token"
session[:token] = #request_token.token
session[:secret] = #request_token.secret
redirect #request_token.authorize_url
end
get '/access_token' do
#request_token = OAuth::RequestToken.new #consumer, session[:token], session[:secret]
#access_token = #request_token.get_access_token oauth_verifier: params[:oauth_verifier]
session[:token] = #access_token.token
session[:secret] = #access_token.secret
session[:userid] = params[:userid]
redirect "#{#base_url}/activity"
end
get '/activity' do
#access_token = OAuth::AccessToken.new #consumer, session[:token], session[:secret]
response = #access_token.get("http://wbsapi.withings.net/v2/measure?action=getactivity&userid=#{session[:userid]}&startdateymd=2014-01-01&enddateymd=2014-05-09")
JSON.parse(response.body)
end
end
For other API endpoints I get an error response of 247 - The userid provided is absent, or incorrect. This is really frustrating. Thanks
So I figured out the answer after copious amount of Googleing and grasping a better understanding of both the Withings API and the OAuth library I was using. Basically Withings uses query strings to pass in API parameters. I though I was going about passing these parameters correctly when I was making API calls, but apparently I needed to explicitly set the OAuth library to use the query string scheme, like so
http_method: :get, scheme: :query_string
This is appended to my OAuth consumer configuration and all worked fine immediately.

Using Ruby + OAuth to access Yelp API

I just getting started with OAuth, and I tried to make a small client to connect to some webservices... I tried twitter and it worked like a charm, however, I also tried to access Yelp V2 API (following their Python example) but I always get back as an answers:
HTTP 400 Bad Request
Missing parameter: oauth_consumer_key
Here's my code:
require 'rubygems'
require 'oauth'
CONSUMER_KEY = "MY_CONSUMER_KEY"
SECRET = "MY_CONSUMER_SECRET"
TOKEN = "MY_TOKEN"
TOKEN_SECRET = "MY_TOKEN_SECRET"
consumer = OAuth::Consumer.new( CONSUMER_KEY,SECRET, {:site => "http://api.yelp.com", :signature_method => "HMAC-SHA1", :scheme => :header})
access_token = OAuth::AccessToken.new( consumer, TOKEN,TOKEN_SECRET)
p access_token.get("/v2/search?location=new+york").body
Regardless to say, that code works with twitter API without any problem (I actually followed twitter's example code)
Cheers and thanks in advance,
Ze
Use :query_string instead of :header and everything will work (at least for me).
Same code, using Signet:
require 'signet/oauth_1/client'
client = Signet::OAuth1::Client.new(
:consumer_key => 'MY_CONSUMER_KEY',
:consumer_secret => 'MY_CONSUMER_SECRET',
:access_token_key => 'MY_TOKEN_KEY',
:access_token_secret => 'MY_TOKEN_SECRET'
)
response = client.fetch_protected_resource(
:uri => 'http://api.yelp.com/v2/search?location=new+york'
)
# The Rack response format is used here
status, headers, body = response
p body
As per the Yelp documentation, the OAuth parameters do not have to be passed in the query string. The fact that the accepted answer resolved the issue indicates to me that there's probably a bug in the oauth gem causing this.

Resources