ruby-on-railsrubyredmine-api

How to post XML string to api Ruby Faraday


I tried to use Faraday library for Ruby to make the next post request for my API: Need to add API-Key = "xxxxxxxxxxxxxxx" to my header and sent XML inside body

<time_entry>
<issue_id>1</issue_id>
<activity_id>9</activity_id>
<hours>1.0</hours>
<comments>Test</comments>
</time_entry>

That works perfect from the postman, but not work when I use the Faraday library.

My code is:

 require 'faraday'
  xml = %&<time_entry><issue_id>1</issue_id><activity_id>9</activity_id><hours>1.0</hours><comments>automatic spent time</comments></time_entry>&


  faraday = Faraday.new do |f|
    f.request :multipart 
    f.request :url_encoded 
    f.adapter :net_http
    f.headers["API-Key"]="xxxxxxxxxxxxxxx"
  end


  payload = {xml: xml}

  faraday.post("http://localhost:3000/time_entries.xml", payload)

I got a next error:

Completed 422 Unprocessable Entity in 8ms (Views: 0.4ms | ActiveRecord: 2.0ms)
Completed 406 Not Acceptable in 19ms (ActiveRecord: 2.9ms)

Solution

  • I use an alternative method - I sent JSON instead of XML, and use 'net/http'

      require "json"
      require 'net/http'
      uri = URI("http://localhost:3000/time_entries.xml")
    

    I create a new Post request, with JSON body, and that works well.

      req = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')
      req["X-Redmine-API-Key"]="xxxxxxxxxxxxxxxxxxxx"
      req.body = {time_entry: {issue_id:1, activity_id:9,hours: hours, comments: "Test" }}.to_json
      res = Net::HTTP.start(uri.hostname, uri.port) do |http|
        http.request(req)
      end