Random Internet Jokes

Learn to Program, Third Edition — by Chris Pine (74 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Chapter 12 Remote Data and APIs | TOC | Respect 👉

The Official Joke API (which certainly sounds official to me) is about as simple as an API can get: it’s a URL that returns a bit of JSON. In fact, you can try it out in your browser if you want.[1] You’ll see that this API returns a small JSON blob that includes a joke stuffed inside — somewhere.

Believe it or not, blob is actually a technical term. It originally was an acronym for Binary Large OBject but over time came to mean a clump of data, not necessarily large or small, so saying “a small JSON blob” is not that weird.

Anyway, the first step is to have your program fetch the JSON blob, parse it, and turn it into a Ruby object. For this to work, you’ll need to require the net/http library for the fetching, and the json library for the parsing.

This API returns a JSON object (as opposed to a JSON array), which the parser uses to construct a Ruby hash (as opposed to a Ruby array). Most APIs return JSON objects.

What does the JSON object that this API returns look like? What kind of data does it hold? Let’s run this code to find out:

​1: require ​"net/http"​
​2: require ​"json"​
​3:
​4: url = URI(​"https://official-joke-api.appspot.com/random_joke"​)
​5:
​6: json_response = Net::HTTP.​get​(url)
​7:
​8: hash_response = JSON.​parse​(json_response)
​9:
​10: puts…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.