How to use Azure ML API with Ruby on Rails - ruby-on-rails
I am using the code with a URL and API key but every time i will get the some error of 405 or 400. Is there any proper way to implement Azure ML API in Rails.
The code as below :-
data = {
"Inputs" => {
"input1" =>
{
"ColumnNames" => #a,
"Values" => [ #writer ]
}, },
"GlobalParameters" => {
}
}
body = data.to_json
puts "adssssssssssssssssssssssssssssss#{body}"
url = "https://ussouthcentral.services.azureml.net/workspaces/5aecd8f887e64999a9c854d724e5/services/5f350fa1b48647ce95c5279eee2170d0/execute?api-version=2.0&details=true"
api_key = 'wGMMQGYlo4tttV+oTjrR/tyt6xYSmWskCezNKkbGwvAVt0wsessJUORQ==' # Replace this with the API key for the web service
headers = {'Content-Type' => 'application/json', 'Authorization' => ('Bearer '+ api_key)}
url = URI.parse(url)
req = Net::HTTP::Get.new(url.request_uri,headers)
http = Net::HTTP.new(url.host, url.port)
res = http.request(req)
{"Inputs":{"input1":{"ColumnNames":["encounter_id","patient_nbr","Fname","Lname","Email","Type","race","gender","Birth Date","Birth Year","age","Age Min","Age Max","weight","admission_type_id","discharge_disposition_id","admission_source_id","time_in_hospital","payer_code","medical_specialty","num_lab_procedures","num_procedures","num_medications","number_outpatient","number_emergency","number_inpatient","number_diagnoses","max_glu_serum","A1Cresult","metformin","repaglinide","nateglinide","chlorpropamide","glimepiride","acetohexamide","glipizide","glyburide","tolbutamide","pioglitazone","rosiglitazone","acarbose","miglitol","troglitazone","tolazamide","examide","citoglipton","insulin","glyburide-metformin","glipizide-metformin","glimepiride-pioglitazone","metformin-rosiglitazone","metformin-pioglitazone","change","diabetesMed","readmitted"],"Values":[[[{"$oid":"56b1ab886e75720ba23b5400"},"","Rana","Warhurst",null,"Patient","Caucasian","Male","2012-10-23","",3,"","","","",null,null,null,"",null,"","","","","","",null,"","No","NO"]]]}},"GlobalParameters":{}}
Using Unirest gem
url = "url for ml"
api = "ml API key"
headers = "same as above"
response = Unirest.post url, headers: headers, parameters: body
response.code
response.headers
response.body
response.raw_body
The result values will be stored in response.body
Related
How to add multiple form_data fields in Net::HTTP::Post request
I want add report and file in my request body. How do I do it? Here is the code, uri = URI("") request = Net::HTTP::Post.new(uri) request['Accept'] = 'application/json' request['Authorization'] = "Bearer token" data = [['file', File.open("./sample_file.pdf")]] request.set_form data, 'multipart/form-data' res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end
How to call JDoodle API from local Rails server?
I am calling the JDoodle API with post request from my local machine Rails server with valid id and secrete. I am not getting desired response. Please suggest me if i am doing wrong.... My Ruby function to make api call def run_Jddodle_API require 'net/http' require 'uri' require 'json' uri = URI.parse("https://api.jdoodle.com/v1/execute") request = Net::HTTP::Post.new(uri) request.content_type = "application/json; charset=UTF-8" request.body = { "clientId" => "ddc371fd*************c8efbae", "clientSecret" => "4ee8e79a225***************************a8ee7f331aeeca603", "script" => "<?php printf(\"hello RAJA\"); ?>", "language" => "php", "versionIndex" => "0" }.to_json 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 end And the response is {"error":"Unauthorized Request","statusCode":401}
try changing this line: request.content_type = "application/json; charset=UTF-8" to this: request.content_type = "application/json"
I changed the code as below and it worked but can't say why.? require 'uri' require 'net/http' require 'net/https' url = URI("https://api.jdoodle.com/v1/execute") http = Net::HTTP.new(url.host, url.port) http.use_ssl = true request = Net::HTTP::Post.new(url.path) request["Content-Type"] = 'application/json' request.body = { "script" => params[:code], "language" => params[:lang], "versionIndex" => params[:version], "clientId" => "dc37******************efbae", "clientSecret" => "4ee8e79a225a5525*******************************************" }.to_json response = http.request(request) puts response.read_body`
Missing query parameters on x-www-form-urlencoded POST request and net/http
I have a post request with headers and query parameters that I want to fire with net/http. The request returns 200 but the response body says: {\"error\":\"invalid_request\",\"error_description\":\"Required query parameter 'grant_type' missing.\"} This is the complete function I call: def Search.request_oauth_access_token require 'net/http' uri = URI.parse('https://request.url/oauth2/access_token') params = { 'grant_type' => 'my:grant:type' } headers = { 'Authorization' => 'Basic sldhfgKGsdfgGOI23==', 'Content-Type' => 'application/x-www-form-urlencoded' } http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Post.new(uri.request_uri, headers) query = URI.encode_www_form_component(params) request.body = query response = http.request(request) p response.body end I am using Rails 5.0.2.
Solved it. Turned out that I had a syntax error in the params definition. This was the correct way of defining it: params = { grant_type: 'my:grant:type' } And then in the request: query = URI.encode_www_form(params) http.request(request, query)
The simplest way is using ruby core library: require "uri" require "net/http" params = { 'field1' => 'Nothing is less important', 'field2' => 'Submit' } x = Net::HTTP.post_form(URI.parse('http://www.yahoo.com/web/ch05/formpost.asp'), params) puts x.body This saved my day
You can also change your params syntax to the following: params = [ [ "param1", "value1" ], [ "param2", "value2" ], [ "param3", "value3" ] ]
Ruby POST with custom headers and body?
I'm trying to POST to Mailchimp in Ruby but I can't get any code working which has custom headers and a body. This is the request I am trying to replicate: curl --request GET \ --url 'https://<dc>.api.mailchimp.com/3.0/' \ --user 'anystring:<your_apikey>' but I also have to add a JSON body. If I run this code: postData = Net::HTTP.post_form(URI.parse('https://xxx.api.mailchimp.com/3.0/lists/xxx/members/'), { ... }}) puts postData.body I get a response from Mailchimp that the apikey is missing. How do I add the API key? Based on these posts: Ruby request to https - "in `read_nonblock': Connection reset by peer (Errno::ECONNRESET)" Ruby send JSON request I tried this: uri = URI('https://xxx.api.mailchimp.com/3.0/lists/xxxx/members/') req = Net::HTTP::Post.new(uri, initheader = {'Content-Type' =>'application/json'}) req.basic_auth 'anystring', 'xxxx' req.body = URI.encode_www_form({ ... }}) response = Net::HTTP.new(uri.hostname, uri.port, :use_ssl => uri.scheme == 'https').start {|http| http.request(req) } puts "Response #{response.code} #{response.message}:#{response.body}" but I get the error TypeError (no implicit of Hash into String) on the response = ... line. What is the error referring to and how do I fix it? UPDATE: using start instead of new: response = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => uri.scheme == 'https') {|http| http.request(req) } I am able to send the request, but I get a 400 response: "We encountered an unspecified JSON parsing error" I get the same response with the posted answer. here is my JSON: {'email_address' => 'xxxx#gmail.com', 'status' => 'subscribed', 'merge_fields' => {'FNAME' => 'xxx', 'LNAME' => 'xxx' } I also tried adding the data like this: req.set_form_data('email_address' => 'xxxx#gmail.com', 'status' => 'subscribed', 'merge_fields' => {'FNAME' => 'xxx', 'LNAME' => 'xxx' } ) but I get the same JSON parse error
Try this, if it works for you uri = URI('https://api.mailchimp.com/3.0/lists/xxxx/members/') Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http| req = Net::HTTP::Post.new(uri) req['Content-Type'] = 'application/json' req.basic_auth 'username', 'password' req.set_form_data('from' => '2005-01-01', 'to' => '2005-03-31') response = http.request req # Net::HTTPResponse object end You need to set form data in post request like req.set_form_data('from' => '2005-01-01', 'to' => '2005-03-31') Updates: Try posting raw data like json_data = {'from' => '2005-01-01', 'to' => '2005-03-31'}.to_json req.body = json_data
POST request to HTTPS using Net::HTTP
This POST request using Ajax works perfectly: var token = "my_token"; function sendTextMessage(sender, text) { $.post('https://graph.facebook.com/v2.6/me/messages?', { recipient: {id: sender}, message: {text:text}, access_token: token }, function(returnedData){ console.log(returnedData); }); }; sendTextMessage("100688998246663", "Hello"); I need to have the same request but in Ruby. I tried with Net:HTTP, but it doesn't work and I don't get any error so I can't debug it: token = "my_token" url = "https://graph.facebook.com/v2.6/me/messages?" sender = 100688998246663 text = "Hello" request = { recipient: {id: sender}, message: {text: text}, access_token: token }.to_json uri = URI.parse(url) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(uri.request_uri) response = http.request(request) response.body How should I proceed to get the error or where did I go wrong ?
Your request hash is being replaced by your request object which you're assigning Net::HTTP. Also be sure to set request params in the body of your HTTP request: require "active_support/all" require "net/http" token = "my_token" url = "https://graph.facebook.com/v2.6/me/messages?" sender = 100688998246663 text = "Hello" request_params = { recipient: {id: sender}, message: {text: text}, access_token: token } request_header = { 'Content-Type': 'application/json' } uri = URI.parse(url) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(uri.path, request_header) request.body = request_params.to_json http.request(request) response = http.request(request) You may find the following reference helpful: http://www.rubyinside.com/nethttp-cheat-sheet-2940.html