jnunemaker / httparty

:tada: Makes http fun again!
MIT License
5.81k stars 964 forks source link

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

Open andyentity opened 7 years ago

andyentity commented 7 years ago

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
jnunemaker commented 7 years ago

It does feel really wrong to turn body into query string stuff. I can't for the life of me remember why it would be that way. I'd be open to a PR that changes that functionality. I'm not sure how I feel about automatic conversion of the body to json or anything, as that seems easily handled by adding to_json to the hash yourself.

tongrhj commented 6 years ago

For future reference, this was the line of code OP was referring to: https://github.com/jnunemaker/httparty/blob/e1f7ae123b9e7df50eeb84be5f350ac9b5ac989a/lib/httparty/request.rb#L167

(and I've checked that it's still there in master as of now)

fabOnReact commented 4 years ago

better using your own libary for http requests wrapped around net/http

I believe it will cause less bugs and be more useful to the developer