Post XML to an external API - Using cURL in Rails - ruby-on-rails

I've been working in the Rails console with Rails 3.2 and I'm generating an XML file using Nokogiri. From here, I need to post to an external API to grab some data and return it within my app. Eventually this code will be a function of the controller, but for now I've been experimenting in the console.
I generated and XML file with Nokogiri and parameters I specified, and I stored the output using the following command:
File.open('results.xml', 'w') {|f| f.write(results)}
From here, I want to POST this file to the external API. The command I used saved it in the /public directory of my app. From here, I'm unsure of how to access it with cURL.
I tried putting it in a views directory and set up a route so I can GET the file, and I can at least access it. Here is what I tried in cURL (note that the Rails server was running at the time and the API path below is made up for example purposes):
curl -X POST -v --data-ascii http://localhost:3000/search/postresults.xml http://APIPATH/example.php
This one has been frustrating me for awhile, and when I try that I get an error saying:
SyntaxError: (irb):5: syntax error, unexpected tCONSTANT, expecting keyword_do or '{' or '('
curl -X POST -v --data-ascii http://local...
^
(irb):5: syntax error, unexpected tUMINUS, expecting keyword_do or '{' or '('
curl -X POST -v --data-ascii http://localhost:...
^
(irb):5: syntax error, unexpected tLABEL, expecting keyword_do or '{' or '('
...l
-X POST -v --data-ascii http://localhost:3000/search/postr...
... ^
(irb):5: unknown regexp options - lcalht
I've tried all of the standard troubleshooting (curl is installed - version 0.0.9, server is running, curl is in my Gemfile, etc), so any help is much appreciated. Thanks!

Your errors suggest that you typed the curl command and arguments directly into IRb. That's not how Ruby gems work. Furthermore, if you want to POST to an HTTP resource from Rails don't bother with cURL. Rails has built-in tools for this.
If you're going to be interacting with this API a lot, and if the API is fairly RESTy, then take a look at ActiveResource (tutorials abound on Google if the docs don't do it for you).
If you're not using a very RESTy API, or if this is a one-off API call, you can create an instance of ActiveResource::Connection directly, e.g.:
conn = ActiveResource::Connection.new 'http://example.com'
result = conn.post 'example.php', results
There's likely no need to write the Nokogiri document (results) to a file, just give it directly to ActiveResource::Connection#post.

Related

RestClient syntax for file uploads

Following the indications provided by this gem , testing in the Rails console the RestClient
RestClient.post "https://upload.twitter.com/1.1/media/upload.json?media_category=tweet_image", :myfile => File.new("/Users/main/Desktop/ss2022-11-03_11.39.11.png", 'rb')
one can assert that the file exists by changing its path. Once verified, the response returns
400 Bad Request. So the request is malformed. Alas, I do not grasp what the second element of the File.new represents
The version 1.1 API documentation provides a suggestion console test
twurl -X POST -H upload.twitter.com "/1.1/media/upload.json?media_category=TWEET_IMAGE&additional_owners=3805104374" -f adsapi-heirarchy.png -F media
the response is the same whether the additional_owners is included or not (logical, it is optional).
What is missing in this sequence?
Thr translation of the twurl syntax to curl syntax would be:
curl "https://upload.twitter.com/1.1/media/upload.json?media_category=tweet_image&additional_owners=3805104374" --data-urlencode #/Users/main/Desktop/adsapi-heirarchy.png --data-urlencode 'media'

syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE)

I am using laravel5.0 on centos 6.9, when I try to run php artisan migarate , getting error PHP Parse error:
syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in /root/.local/share/Trash/files/keystone_laravel.2/laravel/artisan on line 3
please anyone help
Change the version of your php for L5.0 you need to install a
PHP >= 5.4, PHP < 7
https://laravel.com/docs/5.0
I'm using Laravel5.4 and CentOS7.4, and PHP5.4 pre-installed into the system, but I installed php7.0 manually by source-code without link it to /usr/bin so when I run php artisan schedule:run, it actually run the command with php5.4, and of course I get the same error. So I link php7.0 to /usr/bin to make it as default php, then I fixed it.

Use CURL to make a GET request with query parameters

I am making the following curl request from the console to test one of my REST API
curl -X GET "http://localhost/api/v1/user/search.json?search_model[first_name]=abc&auth_token=xyzf"
But it is failing with the following error
curl: (3) [globbing] error: bad range specification after pos 58
I wrapped the endpoint with " because & is used to execute the precious command in console. What else am i missing? Why am i getting this error?
steve>curl --help | grep glob
-g, --globoff Disable URL sequences and ranges using {} and []
Try adding -g.

Writing a curl Post call in Ruby

If i issue a POST request using curl command to github api to add "Resolved" label; things are good.
curl -i -H "Authorization: token xxxxxxxxxxxx" -X POST 'https://git.corp.yahoo.com/api/v3/repos/owner/repo/issues/1/labels' -d '["Resolved"]'}
But when i try to do the same using Curl easy in my Ruby script
set gh_api = https://git.corp.yahoo.com/api/v3/repos/owner/repo/issues/1/labels
curl = Curl::Easy.http_post(settings.gh_api,'["Resolved"]')
do |c|
c.headers = ["Authorization: token xxxxxxxx"]
end
The JSON reponse I get is
"{\"message\":\"Not Found\"}"
What am i doing wrong in my ruby script?
It's not at all clear what question you are asking because there is no question.
What's returned is a JSON response. Why don't you parse it with the JSON class and see what it returns:
require 'json'
puts JSON["{\"message\":\"Not Found\"}"]
=> {"message"=>"Not Found"}
I'm guessing that the problem is in the path of the URL if the response is "Not Found".
My URL was wrong. I ended the URL with a '/'.

check syntax of ruby/jruby script using jruby -c syntax check (inside ruby code)

I am in a search of some way , using which in ruby code I should be able to create a temp file and then append some ruby code in that, then pass that temp file path to jruby -c to check for any syntax errors.
Currently I am trying the following approach:
script_file = File.new("#{Rails.root}/test.rb", "w+")
script_file.print(content)
script_file.close
command = "#{RUBY_PATH} -c #{Rails.root}/test.rb"
eval(command);
new_script_file.close
When I inspect command var, it is properly showing jruby -c {ruby file path}. But when I execute the above piece of code I am getting the following error:
Completed 500 Internal Server Error in 41ms
SyntaxError ((eval):1: dhunknown regexp options - dh):
Let me know if any one has any idea on this.
Thanks,
Dean
eval evaluates the string as Ruby code, not as a command line invocation:
Since your command is not valid Ruby syntax, you get this exception.
If you want to launch a command in Ruby, you can use %x{} or ``:
output1 = ls
output2 = %x{ls}
Both forms will return the output of the launched command as a String, if you want to process it. If you want this output to be directly displayed in the user terminal, you can use system():
system("ls")

Resources