简体   繁体   中英

Sending a JSON to an API Url through Ruby on Rails

I have a json object that I'm sending to Google's QXP Express API. The idea is that I send the object with the relevant travel information. In terminal, through curl, it's very easy to send it. I just use the following curl command. Doc.json is the file name of the json.

curl -d @doc.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=AIzaSyAaLHEBBLCI4aHLNu2jHiiAQGDbCunBQX0

This is my code to do it in Ruby.

uri = URI('https://www.googleapis.com/qpxExpress/v1/trips/search?key=MYAPIKEY')
req = Net::HTTP::Post.new uri.path

req.body = {
  "request" => {
    "passengers" => {
      "adultCount" => 1
    },
    "slice" => [
      {
        "origin" => "BOS",
        "destination" => "LAX",
        "date" => "2014-10-14"
      },
      {
        "origin" => "LAX",
        "destination" => "BOS",
        "date" => "2014-11-14"
      }
    ]
  }
}.to_json

res = Net::HTTP.start(uri.host, uri.port, :use_ssl => true) do |http|
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  http.ssl_version = :SSLv3
  http.request req
end

puts res.body

However I'm getting back the following error.

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "parseError",
    "message": "This API does not support parsing form-encoded input."
   }
  ],
  "code": 400,
  "message": "This API does not support parsing form-encoded input."
 }
}

I just need to send it with the json file, but nothing I can find online covers sending json's to APIs. Please help, I'm very stuck.

It is always matter of taste what tools you prefer, but as for me i am currently using the rest-client gem for accessing REST APIs. With this library your example could be written like this:

require 'json'
require 'rest-client'
response = RestClient.post 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=AIzaSyAaLHEBBLCI4aHLNu2jHiiAQGDbCunBQX0',
             {
               request: {
                 passengers: {
                   adultCount: 1
                 },
                 slice: [
                   {
                     origin: "BOS",
                     destination: "LAX",
                     date: "2014-10-14"
                   },
                   {
                     origin: "LAX",
                     destination: "BOS",
                     date: "2014-11-14"
                   }
                 ]
               }
             }.to_json,
             :content_type => :json
puts response.body

But if you want a Net::HTTP only solution, this might not be a suitable answer for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM