Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faraday JSON post 'undefined method bytesize' for has bodies

Tags:

ruby

faraday

I'm trying to convert some code from HTTParty to Faraday. Previously I was using:

HTTParty.post("http://localhost/widgets.json", body: { name: "Widget" })

The new snippet is:

faraday = Faraday.new(url: "http://localhost") do |config|
  config.adapter Faraday.default_adapter

  config.request :json
  config.response :json
end
faraday.post("/widgets.json", { name: "Widget" })

Which results in: NoMethodError: undefined method 'bytesize' for {}:Hash. Is it possible to have Faraday automatically serialize my request body into a string?

like image 400
Kevin Sylvestre Avatar asked Sep 28 '22 09:09

Kevin Sylvestre


1 Answers

The middleware list requires it be constructed/stacked in a particular order, otherwise you'll encounter this error. The first middleware is considered the outermost, which wraps all others, so the adapter should be the innermost one (or last):

Faraday.new(url: "http://localhost") do |config|
  config.request :json
  config.response :json
  config.adapter Faraday.default_adapter
end

See Advanced middleware usage for additional info.

like image 196
l'L'l Avatar answered Oct 03 '22 03:10

l'L'l