Skip to content

Instantly share code, notes, and snippets.

@nullcookies
Forked from pwightman/httparty.md
Created December 30, 2019 13:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nullcookies/328d2eaa9c06db1bdb07eace10e0524f to your computer and use it in GitHub Desktop.
Save nullcookies/328d2eaa9c06db1bdb07eace10e0524f to your computer and use it in GitHub Desktop.
HTTParty usage

This is a much simpler HTTP library called HTTParty. The standard library that comes with Ruby is quite verbose, you have to convert a string to a URL, specify URLs and ports and all sorts of longwinded stuff. This is much easier. There's both a command line interface, if you just want to test things out for the queue at the command line, for example, as well as a ruby library. I'll show both here. You can install it with gem install httparty.

Command-line usage:

httparty -H Accept:application/json "http://nine.eng.utah.edu/schools"

# Accepts JSON, uses POST instead of GET, and does BASIC authentcation, which the queue requires
# once you've logged in. I can show you that later.
httparty -H Accept:application/json -a post -u username:password "http://nine.eng.utah.edu/schools"

Ruby usage:

require 'httparty' # You don't need this if it's inside a Rails project
                   # and you've included it in your Gemfile.

response = HTTParty.get("http://nine.eng.utah.edu/", headers: { 
  "Accept" => "application/json" 
})

# The response object allows you to get lots of information, like the status code
puts response.code

# This will print the body string, which is just JSON
puts response.body

# And if you do .to_a, it will parse the JSON as an array for you, which is nice.
puts response.to_a

# And if you do .to_h, it will parse it as a hash, though you have to know whether
# you're getting back an array/hash and do the right one

# You can use the above code in your Ticketing system. You can do HTTParty.get/post/put/delete 
# and pass in the URL and headers/authentication/etc. Much more succinct that the standard HTTP 
# library that comes with Ruby
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment