Let us build a simple CLI with ruby and CocktailsDB API
Setup
gems/libraries that will be used:
- Net::HTTP
- open-uri
- json
require 'net/http'
require 'open-uri'
require 'json'
Testing our API
For this demonstration, I will be using the API to search for a drink by name. Fortunately, our API provides an auth key without having to create an account.
https://www.thecocktaildb.com/api/json/v1/1/search.php?s=URL_PARAM
All we need to do is fetch the API with our search query.
https://www.thecocktaildb.com/api/json/v1/1/search.php?s=margarita
*notice I am replacing URL_PARAM
with margarita
at the end of our URL.
After visiting the link we get a json response that looks something like this.
{
drinks: [
{
DRINK_ONE_INFO....
},
{
DRINK_TWO_INFO....
}
]
}
Fetching our API
We'll ask for user input and fetch query to our API endpoint in our fetch_drink_by_name
method.
def fetch_drink_by_name
end
Getting user input
First, we'll prompt the user to enter a search query
puts "enter name of drink"
Then instruct the CLI to wait for input from the user, and store the input in a variable
query = gets.strip
.
Finally, we will save our endpoint in a variable. Notice we are using template literal to add our user's query as a URL parameter.
url = "https://www.thecocktaildb.com/api/json/v1/1/search.php?s=#{query}"
Retrieving our data
Now we will retrieve our data in four simple steps
- Convert URL to URI
- Make a GET request and retrieve the body of the response.
- Parse our JSON data and get info stored in our
drinks
object. - Print results(if any), otherwise print no results message.
I will print our drinks
variable to CLI to make sure everything is working
require 'net/http'
require 'open-uri'
require 'json'
def fetch_drink_by_name
puts "enter name of drink"
query = gets.strip
url = "https://www.thecocktaildb.com/api/json/v1/1/search.php?s=#{query}"
uri = URI.parse(url)
res = Net::HTTP.get_response(uri).body
drinks = JSON.parse(res)["drinks"]
if drinks
puts drinks
else
puts "sorry no results found"
end
end
fetch_drink_by_name
All done, you may use the data however you wish. If everything works correctly your CLI will show an array of objects, with each object containing the drinks data. Or print "sorry no results found" if there were no results.
Top comments (0)