All posts

Ruby http gem cheatsheet

A few notes to refer to when needing to use the ruby http gem.

*This is not a comprehensive post. It is a quick reference if you have some experience with ruby/http but haven’t used it recently.

  1. Updating headers

Say you have your http client defined within a method like this:

def http
  HTTP[
    authorization: "Bearer sometoken",
    accept: "application/json",
    content_type: "application/json"
  ]
end

While building new functionality you realize you want to use this method, but need different headers, you can accomplish this through the headers method on the HTTP object like so:

def update_config
  http
  .headers(accept: "application/x-www-form-urlencoded", content_type: "application/x-www-form-urlencoded")
  .put("https://somebaseurl/configuration", form: config)
end
  1. Post JSON vs Form vs Body

Depending on the Content-Type the server you are calling to is expecting you will need to send different post body options:

When the expected Content-Type is application/json use json::

http.put("https://somebaseurl/configuration", json: config)

When the expected Content-Type is application/x-www-form-urlencoded use form::

http.post("https://somebaseurl/configuration", form: config)

When the expected Content-Type is application/xml use body::

http.post("https://somebaseurl/configuration", body: config)
  1. If some endpoints are expecting an Authorization header and others are not, you can just add the authorization header to the http client as exampled in the first note and if the server does not need authorization it will just ignore it.

Postscript:

I built two products to help fund continued efforts for this website, it would mean a lot if you would check them out:
1. 2500+ Words for the Undermotivated Software Engineer - A short essay I wrote on the titled topic ($3).
2. Build 3 Chrome Extensions in Under 2 Hours - A course I built to teach chrome extension development ($9-20).