jnunemaker / jnunemaker/httparty

Don't use a the query string normalizer to transform the body

Open
#516 2 comments 4 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Ruby
Stars
5.9k
Forks
973
Avg merge
1h 59m
Merged PRs (30d)
1

Description

Scenario:
I want to communicate with a JSON API. I want to do a post request with a JSON body and for this I want to pass a hash into the body.

class Abc
  include HTTParty
  format :json
....
  def self.authorize
    r = post('/auth/local', body: { email: username, password: password })
  end
end

What happens is, that this hash, instead of being serialized into a json-string, it is parsed into a query string.
https://github.com/jnunemaker/httparty/blob/master/lib/httparty/request.rb#L167

Instead, I would like to specify a Proc/Class/whatever, like for the query string normalizer, but for the body payload, in order to process the value that I passed for the body into the post method.

Also, generally it makes sense to expect a Hash in the body of a request when dealing with a JSON API. Here's a monkeypatch that enables this and makes the above example work (in Ruby on Rails). It transforms the body automatically when the format is set accordingly:

require 'httparty'

module HTTParty
  module ClassMethods

    private

    def perform_request(http_method, path, options, &block)
      options = ModuleInheritableAttributes.hash_deep_dup(default_options).merge(options)
      process_headers(options)
      process_body(options) # This line was added
      process_cookies(options)
      Request.new(http_method, path, options).perform(&block)
    end

    def process_body(options)
      return unless options[:body]

      if (options[:format] == :json) and options[:body].respond_to?(:to_json)
        options[:body] = options[:body].to_json # Ruby on Rails specific, converts a Hash into a JSON-String
      end
    end

  end

end

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in lib/httparty/request.rb at the body handling around line 167, then trace the request path used by perform_request and the format option. Compare the existing query-string normalization with the issue's process_body example. Done means JSON API requests can pass a Hash body without it being converted to a query string, while other body formats retain their expected behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
ruby
Domain
api, backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.