Search code examples
rubyrest-client

How to create a custom header starting with underscore


I have a RESTful API provider who is insisting on using a POST call with a header _method set to DELETE as a workaround for their DELETE calls not working.

This is how I think the syntax should be:

response = RestClient.post("path/to/url", "{}",
            {
                    :content_type => 'application/json; charset=UTF-8',
                    :accept => 'application/json; charset=UTF-8',
                    :'_method' => "DELETE"
            } )

However the header is being morphed as shown below running with RESTCLIENT_LOG=stdout

RestClient.post "<snipped>", "{}", "-Method"=>"DELETE", "Accept"=>"application/json; charset=UTF-8", "Accept-Encoding"=>"gzip, deflate", "Content-Length"=>"2", "Content-Type"=>"application/json; charset=UTF-8" 

As can be seen _method becomes -Method. How can I have a customer header with a key named _method please?


Solution

  • It looks like rest-client has special treatment for Symbol keys in the headers Hash, to convert e.g. :content_type into "Content-Type", which is nice and convenient.

    The solution to your problem is to use a String instead:

    response = RestClient.post("path/to/url", "{}",
                 :content_type => 'application/json; charset=UTF-8',
                 :accept => 'application/json; charset=UTF-8',
                 "_method" => "DELETE"
               )