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
    authorization: "Bearer sometoken",
    accept: "application/json",
    content_type: "application/json"

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
  .headers(accept: "application/x-www-form-urlencoded", content_type: "application/x-www-form-urlencoded")
  .put("https://somebaseurl/configuration", form: config)
  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:"https://somebaseurl/configuration", form: config)

When application/xml:"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.