5

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?

Kevin Sylvestre
  • 37,288
  • 33
  • 152
  • 232
  • 1
    Try putting adapter last in the middleware list — see [Advanced middleware usage](https://github.com/lostisland/faraday). – l'L'l Apr 08 '15 at 04:19
  • @l'L'l That is definitely the bug. Can you add an answer instead of a comment so I can accept + bounty? – Kevin Sylvestre Apr 10 '15 at 23:16

2 Answers2

5

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.

l'L'l
  • 44,951
  • 10
  • 95
  • 146
-2

You can always create your own middleware for Faraday.

require 'faraday'

class RequestFormatterMiddleware < Faraday::Middleware
  def call(env)
    env = format_body(env)
    @app.call(env)
  end

  def format_body(env)
    env.body = 'test' #here is any of needed operation
    env
  end
end

conn = Faraday.new("http://localhost") do |c|
  c.use RequestFormatterMiddleware
end

response = conn.post do |req|
 req.url "http://localhost"
 req.headers['Content-Type'] = 'application/json'
 req.body = '{ "name": "lalalal" }' 
end

p response.body #=> "test"
dolgishev
  • 44
  • 5
  • Why did you vote down? With own middleware you can do serialisation easily. – dolgishev Apr 08 '15 at 19:31
  • 2
    I down voted because this was a bad solution. @I'L'I's comment is the correct solution. The advice of writing custom middleware to fix a parameter ordering issue (which was the only problem) is absurd. – Kevin Sylvestre Apr 10 '15 at 23:19