docs/middleware/included/json.md
The JSON request middleware converts a Faraday::Request#body hash of key/value pairs into a JSON request body.
The middleware also automatically sets the Content-Type header to application/json,
processes only requests with matching Content-Type or those without a type and
doesn't try to encode bodies that already are in string form.
conn = Faraday.new(...) do |f|
f.request :json
...
end
conn.post('/', { a: 1, b: 2 })
# POST with
# Content-Type: application/json
# Body: {"a":1,"b":2}
By default, middleware utilizes Ruby's json to generate JSON strings.
Other encoders can be used by specifying encoder option for the middleware:
dumprequire 'oj'
Faraday.new(...) do |f|
f.request :json, encoder: Oj
end
Faraday.new(...) do |f|
f.request :json, encoder: [Oj, :dump]
end
The JSON response middleware parses response body into a hash of key/value pairs.
The behaviour can be customized with the following options:
/\bjson$/.response.env[:raw_body] property. Defaults to false.conn = Faraday.new('http://httpbingo.org') do |f|
f.response :json, **options
end
conn.get('json').body
# => {"slideshow"=>{"author"=>"Yours Truly", "date"=>"date of publication", "slides"=>[{"title"=>"Wake up to WonderWidgets!", "type"=>"all"}, {"items"=>["Why <em>WonderWidgets</em> are great", "Who <em>buys</em> WonderWidgets"], "title"=>"Overview", "type"=>"all"}], "title"=>"Sample Slide Show"}}
By default, middleware utilizes Ruby's json to parse JSON strings.
Other decoders can be used by specifying decoder parser option for the middleware:
loadrequire 'oj'
Faraday.new(...) do |f|
f.response :json, parser_options: { decoder: Oj }
end
Faraday.new(...) do |f|
f.response :json, parser_options: { decoder: [Oj, :load] }
end