Get request rails 5.1 - ruby-on-rails

Hi i want to "connect" my "Exemple.html.erb" to an API, in this view i want to show some information that i want from this api adress "https://api.exemple.com"
I have the address api and api key.
So how to do a get request from this api address and show the result in my view.
I tried this code and it's not working:
require 'httparty'
url = 'https://api.exemple.com'
headers = { key1: 'apikey', key2: 'mykeynumber' }
response = HTTParty.get(url, headers: headers)
puts response.body

I believe if you are using erb and want to print inside using Ruby code, you have to wrap any Ruby code with <%= %>, assuming this code you have is in file you mentioned you could try:
.rb file:
require 'httparty'
url = 'https://api.exemple.com'
headers = { key1: 'apikey', key2: 'mykeynumber' }
#response = HTTParty.get(url, headers: headers)
.erb file:
<%= #response.body %>

Related

How to format HTTParty POST request?

I've been playing around with API calls for a project I'm working on and I'm getting a problem when I try to pass some JSON to a POST request. The call works in Postman, but I just can't figure out how to format it in Ruby. Here's my code:
require 'httparty'
require 'json'
require 'pp'
#use the HTTParty gem
include HTTParty
#base_uri 'https://app.api.com'
#set some basic things to make the call,
#apiUrl = "https://app.api.com/"
#apiUrlEnd = 'apikey=dontStealMePls'
#apiAll = "#{#apiUrl}#{#apiUrlEnd}"
#apiTest = "https://example.com"
def cc_query
HTTParty.post(#apiAll.to_s, :body => {
"header": {"ver": 1,"src_sys_type": 2,"src_sys_name": "Test","api_version": "V999"},
"command1": {"cmd": "cc_query","ref": "test123","uid": "abc01", "dsn": "abcdb612","acct_id": 7777}
})
end
def api_test
HTTParty.post(#apiTest.to_s)
end
#pp api_test()
pp cc_query()
This code gives me this error:
{"fault"=>
{"faultstring"=>"Failed to execute the ExtractVariables: Extract-Variables",
"detail"=>{"errorcode"=>"steps.extractvariables.ExecutionFailed"}}}
I know that error because I would get it if I tried to make a call without any JSON in the body of the call (through Postman). So from that I assume that my code above is not passing any JSON when making an API call. Am I formatting my JSON incorrectly? Am I even formatting the .post call correctly? Any help is appreciated! :)
the api_test() method just makes a POSt call to example.com and it works (saving my sanity).
Just use HTTParty as a mixin instead in a class instead:
require 'httparty'
class MyApiClient
include HTTParty
base_uri 'https://app.api.com'
format :json
attr_accessor :api_key
def initalize(api_key:, **options)
#api_key = api_key
#options = options
end
def cc_query
self.class.post('/',
body: {
header: {
ver: 1,
src_sys_type: 2,
src_sys_name: 'Test',
api_version: 'V999'
},
command1: {
cmd: 'cc_query',
ref: 'test123',
uid: 'abc01',
dsn: 'abcdb612',
acct_id: 7777
}
},
query: {
api_key: api_key
}
)
end
end
Example usage:
MyApiClient.new(api_key: 'xxxxxxxx').cc_query
When you use format :json HTTParty will automatically set the content type and handle JSON encoding and decoding. I'm guessing thats where you failed.

Seeding Data from JSON API to Ruby on Rails APP

I'm getting a no implicit conversion of String into Integer error that has me stumped, and unable to import user records and seed my database with them.
So far I have no problem accessing the data, but receive an error referencing the '[]' on the line with User.find... on it
The code I'm using is as follows:
require 'net/http'
require 'uri'
require 'json'
require 'faker'
#this script imports APR user data from the zendesk api and populates
the database with it.
uri = URI.parse("https://blahsupport.zendesk.com/api/v2/users.json")
request = Net::HTTP::Get.new(uri)
request.content_type = "application/json"
request.basic_auth("blah#blah.com", "blahpass")
req_options = {
use_ssl: uri.scheme == "https",
}
#response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
puts #response.body
puts #response.message
puts #response.code
info = #response.body
info.force_encoding("utf-8")
File.write('blahusers1.json', info)
puts "File Created Successfully!"
file = File.read('blahusers1.json')
users = JSON.load(file)
users.each do |a|
User.find_or_create_by_zendesk_id(:zendesk_id => a['id'], :url => a['url'], :name => a['name'], :email => a['email'])
end
Any ideas on how I've gotten this error? Thank you for any help!
**Edit
Below is an example of the data being returned.
{"users":[{"id":333653859,"url":"https://blahblah.zendesk.com/api/v2/users/333653859.json","name":"Randy Blah","email":"randy#blah.com","created_at":"2014-08-06T14:31:24Z","updated_at":"2018-04-04T14:22:06Z","time_zone":"Pacific Time (US & Canada)","phone":null,"shared_phone_number":null,"photo":{"url":"https://aprtechsupport.zendesk.com/api/v2/attachments/68955389.json","id":68955389,"file_name":"Work.jpg","content_url":"https://aprtechsupport.zendesk.com/system/photos/6895/5389/Work.jpg","mapped_content_url":"https://blahblah.zendesk.com/system/photos/6895/5389/Work.jpg","content_type":"image/jpeg","size":2528,"width":80,"height":80,"inline":false,"thumbnails":[{"url":"https://blahblah.zendesk.com/api/v2/attachments/68955399.json","id":68955399,"file_name":"Work_thumb.jpg","content_url":"https://blahblah.zendesk.com/system/photos/6895/5389/Work_thumb.jpg","mapped_content_url":"https://blahblah.zendesk.com/system/photos/6895/5389/Work_thumb.jpg","content_type":"image/jpeg","size":2522,"width":32,"height":32,"inline":false}]},"locale_id":1,"locale":"en-US","organization_id":null,"role":"admin","verified":true,"external_id":null,"tags":[],"alias":"","active":true,"shared":false,"shared_agent":false,"last_login_at":"2018-04-04T14:21:44Z","two_factor_auth_enabled":null,"signature":"Thanks for contacting the helpdesk!\n-Randy","details":"","notes":"","role_type":null,"custom_role_id":null,"moderator":true,"ticket_restriction":null,"only_private_comments":false,"restricted_agent":false,"suspended":false,"chat_only":false,"default_group_id":21692179,"user_fields":{}}
The example data you posted has a root object users that contains the array of user objects. So when you loop users using users.each, a is actually an Array and not a user Hash like you expected.
When you try to access an element of an Array using a 'String' index, it gives you the exception – no implicit conversion of String into Integer
So, try changing
users = JSON.load(file)
to
users = JSON.load(file)['users']
to get it working like how you'd expect.

Translating a curl command to httparty

I want to consume some API data from a Rails app. A curl example is curl --data 'api_key=your_api_key&api_secret=your_api_secret&host_id=your_user_host_id' https://api.zoom.us/v1/webinar/list I have experimented with this at the terminal and I am seeing expected responses. I’m now experimenting in a ruby script using httparty. My question is how should I handle the ‘stuff’ before the endpoint (api_key…secret…ect)? Are these headers?
In regard to curl --data only tells me that it is a post request, but I'm not sure how that translates to httparty.
Here is a first attempt:
require 'httparty'
api_key = 'myKey'
api_secret = 'secret'
host_id = 'host'
data_type = 'JSON'
response = HTTParty.post("api_key&api_secret&host_id&data_type https://api.zoom.us/v1/webinar/list/registration")
puts response.parsed_response
But this gives me a bad URI response. If I run this same script with the endpoint only I do get a response code back from zoom saying that API key and secret are required.
Looking at this example I think this should work:
require 'httparty'
api_key = 'myKey'
api_secret = 'secret'
host_id = 'host'
data_type = 'JSON'
options = {
body: {
api_key: api_key,
api_secret: api_secret,
host_id: host_id,
data_type: data_type
}
}
response = HTTParty.post("https://api.zoom.us/v1/webinar/list/registration", options)
puts response.parsed_response
I get the response:
{"error"=>{"code"=>200, "message"=>"Invalid api key or secret."}}
which I think is a step in the right direction.
No those are not headers those are parameters. Header are usually denoated by the -H flag.
Try this:
require 'httparty'
query_params = {api_key: 'myKey',
api_secret: 'secret',
host_id: 'host',
data_type: 'JSON'}
response = HTTParty.post("api_key&api_secret&host_id&data_type https://api.zoom.us/v1/webinar/list/registration", :query => query_params)
puts response.parsed_response

Rails + HTTParty : Expecting JSON data in the body

I want to integrate the Routific API into a Rails application. I made my request with HTTParty but I get the following message {"error"=>"Expecting JSON data in the body"}
I don't understand... I am sending the json in the body. Please check my code below.
Thanks for your help
Julien
file = File.read("#{Rails.root}/app/controllers/demo.json")
api_key = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ODE3M2ZiNTk1NzRjZTFiMmZhNWEwNTAiLCJpYXQiOjE0Nzc5MTg2NDZ9.extq0nKtPGwj6VXxMpj9u8uapasKVSorWeTBFW7HgOE"
headers = {
"Content-Type:" => "application/json",
'authorization'=> 'bearer ' + api_key
}
#results = HTTParty.post("https://api.routific.com/v1/vrp",
:headers => headers,
:body => file.to_json)
you added invalid headers
it should be "Content-Type" instead of "Content-Type:" (without colon)

Ruby: HTTParty: can't format XML POST data correctly?

NOTE: "object" is a placeholder work, as I don't think I should be saying what the controller does specifically.
so, I have multiple ways of calling my apps API, the following works in the command line:
curl -H 'Content-Type: application/xml' -d '<object><name>Test API object</name><password>password</password><description>This is a test object</description></object>' "http://acme.example.dev/objects.xml?api_key=1234"
the above command generates the following request in the devlog:
Processing ObjectsController#create to xml (for 127.0.0.1 at 2011-07-07 09:17:51) [POST]
Parameters: {"format"=>"xml", "action"=>"create", "api_key"=>"1234", "controller"=>"objects",
"object"=>{"name"=>"Test API object", "description"=>"This is a test object", "password"=>"[FILTERED]"}}
Now, I'm trying to write tests for the actions using the API, to make sure the API works, as well as the controllers.
Here is my current (broken) httparty command:
response = post("create", :api_key => SharedTest.user_api_key, :xml => data, :format => "xml")
this command generates the following request in the testlog:
Processing ObjectsController#create to xml (for 0.0.0.0 at 2011-07-07 09:37:35) [POST]
Parameters: {
"xml"=>"<object><name><![CDATA[first post]]></name>
<description><![CDATA[Things are not as they used to be]]></description>
<password><![CDATA[WHEE]]></password>
</object>",
"format"=>"xml",
"api_key"=>"the_hatter_wants_to_have_tea1",
"action"=>"create",
"controller"=>"objects
So, as you can see, the command line command actually generates the object hash from the xml, whereas the httparty command ends up staying in xml, which causes problems for the create method, as it needs a hash.
Any ideas / proper documentation?
Current documentation says that post takes an url, and "options" and then never says what options are available
**EDIT:
as per #Casper's suggestion, my method now looks like this:
def post_through_api_to_url(url, data, api_key = SharedTest.user_api_key)
response = post("create", {
:query => {
:api_key => api_key
},
:headers => {
"Content-Type" => "application/xml"
},
:body => data
})
ap #request.env["REQUEST_URI"]
assert_response :success
return response
end
unfortunately, the assert_response fails, because the authentication via the api key fails.
looking at the very of of the request_uri, the api_key isn't being set properly... it shows:
api_key%5D=the_hatter_wants_to_have_tea1"
but it should just be equals, without the %5D (right square bracket)
I think this is how you're supposed to use it:
options = {
:query => {
:api_key => 1234
},
:headers => {
"Content-Type" => "application/xml"
},
:body => "<xmlcode>goes here</xmlcode>"
}
post("/create", options)
Forgive me for being basic about it but if you only want to send one variable as a parameter, why don't you do as Casper suggests, but just do:
post("/create?api_key=1234", options)
Or rather than testing HTTParty's peculiarities in accessing your API, perhaps write your tests using Rack::Test? Very rough example...
require "rack/test"
require "nokogiri"
class ObjectsTest < Test::Unit::TestCase
include Rack::Test::Methods
def app
MyApp.new
end
def create_an_object(o)
authorize "x", "1234" # or however you want to authenticate using query params
header 'Accept', 'text/xml'
header 'Content-Type', 'text/xml'
body o.to_xml
post "/create"
xml = Nokogiri::XML(last_response.body)
assert something_logic_about(xml)
end
end

Resources