Skip to content
No GUI edited this page Apr 7, 2018 · 5 revisions

The HTTP gem uses the concept of chaining to simplify requests. Let's say you want to get the latest commit of this library from GitHub in JSON format. One way we could do this is by tacking a filename on the end of the URL:

HTTP.get("https://github.com/httprb/http/commit/HEAD.json")

The GitHub API happens to support this approach, but really this is a bit of a hack that makes it easy for people typing URLs into the address bars of browsers to perform the act of content negotiation. Since we have access to the full, raw power of HTTP, we can perform content negotiation the way HTTP intends us to, by using the Accept header:

HTTP.headers(:accept => "application/json")
  .get("https://github.com/httprb/http/commit/HEAD")

This requests JSON from GitHub. GitHub is smart enough to understand our request and returns a response with Content-Type: application/json.

Shorter alias exists for HTTP.headers:

HTTP[:accept => "application/json"]
  .get("https://github.com/httprb/http/commit/HEAD")

See also