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 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 is expecting you will need to send different post body options:

When application/json:

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

When application/x-www-form-urlencoded:

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

When application/xml:

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 like above and if the server does not need authorization it will just ignore it.