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.
- 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
- Post JSON vs Form vs Body
Depending on the
Content-Type the server is expecting you will need to send different post body options:
http.put("https://somebaseurl/configuration", json: config)
http.post("https://somebaseurl/configuration", form: config)
http.post("https://somebaseurl/configuration", body: config)
If some endpoints are expecting an
Authorizationheader 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.