I'm running a Ruby app on Heroku. The app returns a JSON which is accessible when I go to the debugger of my browser. The JSON response is of the following template:
rates = {
"Aluminium" => price[1],
"Copper" => price_cu[1],
"Lead" => price_pb[1],
"Nickel" => price_ni[1],
"Tin" => price_sn[1],
"Zinc" => price_zn[1],
}
Sample response:
{
"Aluminium":"1765.50",
"Copper":"7379.00",
"Lead":"2175.00",
"Nickel":"14590.00",
"Tin":"22375.00",
"Zinc":"2067.00"
}
the code i wrote to achieve this is:
Test.rb
class FooRunner
def self.run!
#calculations_for_rates
rates.to_json
end
if __FILE__ == $0
puts FooRunner.run!
end
app.rb
require 'sinatra'
require './test.rb'
result = FooRunner.run!
File.open('output.json','w') do |f|
f.write result
end
content_type :json
result
When I try to access this link using
$.getJSON('app-url',function(data){
console.log(data);
});
it gives me an error saying
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Is there a way for me to directly access the JSON response by writing the JSON to the HTTP response?
So I am guessing that the page you are making the get request from is not served up by Sinatra. You can add the header Access-Control-Allow-Origin: * to that request to make it work.
This answer shows how to do it by either using response['Access-Control-Allow-Origin'] = * or headers( "Access-Control-Allow-Origin" => "*" )
That answer also lists this blog post as a reference to Cross Origin Resource Sharing in Sinatra.
Related
The HTTParty methods are like HTTParty.XXX(urlGoesHere, and Args Here)
I'm doing the following:
params = {:UserName => "uname", :Password => "pwd"}
cookie_hash = HTTParty::CookieHash.new
cookie_hash.add_cookies("key1=val1")
cookie_hash.add_cookies("key2=val2")
options = {
:body=>params,
:headers => { 'Cookie' => cookie_hash.to_cookie_string,
'Accept' => something },
:follow_redirects => false
}
URLUserNamePwd = HTTParty.post(myURL, options) # Is this the right way to do?
When I check the http status code, body I get nothing. When I check in the browser development console, I see 302 redirect, and in response headers I see lot of header pairs returned.
What is the URL you're attempting to hit? 302 Found will be paired with a Location header containing the URL where the resource can be found.
I have an endpoint in my Sinatra application that will be receiving binary data as part of the body. The other application sending it data will have a Faraday request that looks like this:
connection = Faraday.new(url: "https://example.com/post_data") do |conn|
conn.request :multipart
conn.adapter :net_http
conn.headers['Content-Type'] = 'octet/stream'
end
#response ||= connection.post do |req|
req.params = { :host => host,
:verification => "false"}
req.body = my_base64_encoded_binary
end
Then, in Sinatra, I will have an endpoint that receives those request parameters and binary data and passes it along to a model, like so:
post '/post_data' do
request.body.rewind
payload = request.body.read
raise Sinatra::NotFound unless payload and params[:host]
output = MyOutput.new(params, payload)
content_type 'application/json'
body output.data
end
When I try to test this endpoint using Rack::Test helpers, I end up in a weird situation. I can't seem to create the proper mock in order to test this endpoint properly. Based on some manual testing with PostMan, I'm pretty certain my endpoint works properly. It's just the test that's holding me up. Here is the spec:
it "should return a json response" do
post(url, :host => host, :verification => "false") do |req|
req.body = [my_binary]
req.content_type = "application/octet-stream"
end
expect(last_response.status).to eq(200)
expect(last_response.content_type).to eq("application/json")
end
And when I inspect what the incoming request looks like in the test, it does not contain a proper body. params is properly set to the host and verification settings I set, but the body is also being set to the params (inspected through payload = request.body.read) instead of the binary.
Is there a different way to set up the mock so that the binary properly is set to the body of the request, and the parameters are still set to the request parameters properly?
The answer is that the only way to post the body is where I was adding the params in the rack test helper. I needed to take the params and move them into the query string of the URL in the request, and then only add the binary as the body of the post request in the test helper.
let(:url) { "http://example.com/post_data?host=>#{host}&verification=#{verification}" }
it "should return a json response" do
post(url, my_binary)
expect(last_response.status).to eq(200)
expect(last_response.content_type).to eq("application/json")
end
I use ruby with sinatra and I used rest-client on import for payment.
I got token that string typed through post method on specific url: '... /users/getToken'.
Using this token, I wanna get payments information with get method on this url:
get_url = 'https://api/iamport.kr/payments/'+imp_uid
the detail codes are below,
def get_paymentsdetails(token, imp_uid)
get_url = 'https://api.iamport.kr/payments/'+imp_uid
response = RestClient.get get_url, :data => {}.to_json, :accept => :json, :headers => {'Authorization' => token}
json = JSON.parse(response, :symbolize_names => true)
# json = JSON.parse(response.to_json, {:symbolize_names => true})
return json
end
However, I got 401 unauthorized error on this part of code.
response = RestClient.get get_url, :data => {}.to_json, :accept => :json, :headers => {'Authorization' => token}
After I access get_url with specific imp_uid, I got this page,{"code":-1,"message":"Unauthorized","response":null}
I checked parameter token and imp_uid of get_paymentsdetails function have valid string values,, so How can I access response parameter??
I think that there are some problems on response = RestClient.get get_url.... code.
Thanks.
Method 'get' from the 'RestClient' class return some object with attributes. So response have few values. Which of them do you need? Access to them you can get by their names, its described here.
In your case, after response = RestClient.get get_url... you should have variable response and ability to call response.headers, response.code or response.body.
But im afraid that you have some problems with autorization, which means that imp_uid or token is not correct. Thats why remote server sended to you responce with http-code 401 (Unauthorized). If it is so you should try to check your imp_uid and token. If everything is correct try to reach support of iamport.kr .
This is the curl request I'd like to perform:
curl --request GET --url 'https://us8.api.mailchimp.com/3.0/' --user 'anystring:<apikey>'
Running this curl command from the command line, I get a bunch of JSON, which is what I want.
I'm trying to perform this same request using Faraday. This is what I've tried:
conn = Faraday.new "https://us8.api.mailchimp.com/3.0/" do |faraday|
faraday.adapter Faraday.default_adapter
end
conn.basic_auth('apikey', <apikey>)
response = conn.get
puts response.body # => "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n<html><head>\n<title>301 Moved Permanently</title>\n</head>...
How do I get JSON instead of the html I'm seeing in response.body?
This ended up working for me:
conn = Faraday.new('https://us8.api.mailchimp.com/3.0/') do |c|
c.use FaradayMiddleware::ParseJson, content_type: "application/json"
c.use Faraday::Adapter::NetHttp
end
conn.basic_auth('apikey', <api_key>)
response = conn.get('campaigns')
puts response # => json blob
A much more concise option is to manually encode your credentials into Base64 and set the Authorization header manually. This saves a few lines of code and keeps it in a similar format to regular Faraday requests (i.e. Faraday.post <URL>, <BODY>, <HEADERS>).
i.e.
encoded_credentials = Base64.encode64('apikey:api_secret').chomp
Faraday.post 'http://myhost.local/my_url', {}, authorization: "Basic #{encoded_credentials}"
This is the farday code for curl operations using ruby gem.
def contacts
response = JSON.parse(params)
#conn = Faraday.new('https://domain.example.com/api/v2/') do |farday|
farday.use FaradayMiddleware::ParseJson, content_type: "application/json"
farday.use Faraday::Adapter::NetHttp
end
#conn.basic_auth('apikey', <your_api_key>)
response = #conn.get('contacts')
puts response
render :json => {"success" => true}
end
this is my code and I don't know how to debug it because I just get an "internal server error":
I am trying to HTTP POST to an external ASPX:
def upload
uri = 'https://api.postalmethods.com/2009-02-26/PostalWS.asmx' #postalmethods URI
#https://api.postalmethods.com/2009-02-26/PostalWS.asmx?op=UploadFile
#http://www.postalmethods.com/method/2009-02-26/UploadFile
#postalcard = Postalcard.find(:last)
#Username=string&Password=string&MyFileName=string&FileBinaryData=string&FileBinaryData=string&Permissions=string&Description=string&Overwrite=string
filename = #postalcard.postalimage.original_filename
filebinarydata = File.open("#{#postalcard.postalimage.path}",'rb')
body = "Username=me&Password=sekret&MyFileName=#{filename}&FileBinaryData=#{filebinarydata}"
#response = RestClient.post(uri,
body, #body as string
{"Content-Type" => 'application/x-www-form-urlencoded',
"Content-Length" => #postalcard.postalimage.size} # end headers
) #close arguments to Restclient.post
end
Turns on PostalMethods had an error and bug on their HTTP POST.
It only takes SOAP so I would need Savon.