Skip to content

Parsing responses

David Reese edited this page Sep 28, 2018 · 5 revisions

Middleware for parsing responses

Available middleware:

  • FaradayMiddleware::ParseJson
  • FaradayMiddleware::ParseXml
  • FaradayMiddleware::ParseYaml
  • FaradayMiddleware::ParseMarshal

Example use:

## in Faraday 0.8 or above:
connection = Faraday.new 'http://example.com/api' do |conn|
  conn.response :xml,  :content_type => /\bxml$/
  conn.response :json, :content_type => /\bjson$/

  conn.adapter Faraday.default_adapter
end

json_response = connection.get('user/1.json')
json_response.body  #=> { ... }

xml_response = connection.get('user/1.xml')
xml_response.body  #=> { ... }

Dependencies

  • ParseJson: "json" library on ruby distributions that don't have it embedded, such as ruby older than 1.9
  • ParseXml: "multi_xml"
  • ParseYaml: nothing
  • ParseMarshal: nothing

Content type restriction

Each of the parsing middleware can be configured to only parse responses with a specific content-type:

conn.response :json, :content_type => 'application/json'

Now if the response has, for instance, a "text/plain" type, the ParseJson middleware would leave it intact.

However not all JSON responses will be strictly of "application/json" type; consider vendor-specific types such as in GitHub API:

application/vnd.github.beta+json

Because of such variants, it's better to configure type matching with a loosely defined regex:

conn.response :json, :content_type => /\bjson$/

The :content_type param is optional and, if omitted, the middleware will parse every response regardless of its content-type.

Parser Options

The following parsers allows to specify some options to be given to the underlying parser:

  • FaradayMiddleware::ParseJson
  • FaradayMiddleware::ParseXml
  • FaradayMiddleware::ParseYaml

In order to do so, you simply need to pass the parser_options option when configuring them:

conn.response :json, :parser_options => { :symbolize_names => true }

One example use is telling the JSON parser to return OpenStruct objects instead of Hashes:

conn.response :json, :parser_options => { :object_class => OpenStruct }

(Please note: This wiki has been closed, and turned into in-repo Markdown documents. You can find them in the repository's docs/ directory. This wiki does not take new edits.)

Clone this wiki locally