5

I want to send a POST request to an API. Here's my code:

conn = Faraday.new(url: BASE) do |faraday|
  faraday.response :logger
  faraday.request  :url_encoded
  faraday.headers['Content-Type'] = 'application/json'
  faraday.headers["Authorization"] = "bearer #{AppConfig.instance.access_token}"
  faraday.adapter Faraday.default_adapter
end
form_data = {a: 1, b: 2}
conn.post("/api/test", form_data)

But I get this error:

NoMethodError (undefined method `bytesize' for {:a=>1, :b=>2}:Hash)

I've also tried:

conn.post("/api/test", form_data.to_json)

but it doesn't work either.

Stefan
  • 109,145
  • 14
  • 143
  • 218
bav ko ten
  • 502
  • 7
  • 24
  • This is a nice library for making HTTP requests in ruby: https://ruby-doc.org/stdlib-2.5.1/libdoc/net/http/rdoc/Net/HTTP.html – Jagdeep Singh May 25 '18 at 07:45
  • This error is may be because of the `form_data` is not in proper json format. – Ahmad hamza May 25 '18 at 07:58
  • 3
    The result of `to_json` definitely responds to `bytesize`: `form_data.to_json.respond_to?(:bytesize) #=> true` – Michael Kohl May 25 '18 at 08:23
  • Should be fine. Just tried to make a post request with your setup and everything was ok. `conn.post("https://google.com/api/test", {a: 1, b: 2}.to_json)` => `#` – Vitaly May 25 '18 at 08:34
  • What happens when you run your second code (the one with `form_data.to_json`) – do you get the same error or another one? – Stefan May 25 '18 at 08:53

2 Answers2

6

Official faraday repo provides next description:

# post payload as JSON instead of "www-form-urlencoded" encoding:
conn.post do |req|
  req.url '/nigiri'
  req.headers['Content-Type'] = 'application/json'
  req.body = '{ "name": "Unagi" }'
end

So, content type 'application/json' can't resolve hash. Gem doesn't convert the body data to needed format by itself.

You need to convert your form_data to string(json) format:

form_data = {a: 1, b: 2}.to_json

Note. Don't convert by .to_s when using symbol keys format because that will cause the parsing error.

With provided by you faraday configuration I can't cause any error after converting format_data to json. So, new error not related to faraday gem or provided code.

Leo
  • 1,673
  • 1
  • 13
  • 15
  • _"cause the parsing error"_ / _"new error not related to faraday"_ – which other error are you referring to? – Stefan May 25 '18 at 11:29
  • "which other error are you referring to?" - there is no any other error – Leo May 25 '18 at 11:54
0

Use to_json to convert it to json, It fails with as_json as well.

{ key: value }.as_json.respond_to?(:bytesize) => false

{ key: value }.to_json.respond_to?(:bytesize) => true
A. KUMAR
  • 330
  • 1
  • 9