Example: The latest XKCD in Python

In this notebook we fetch and display the latest XKCD strip using both regular Python and special IPython features.

Also this notebook is associated with IPython kernel, and may therefore contain Python code.

Assigning variables

We have been given the XKCD API https://xkcd.com/info.0.json for fetching information of the latest strip in JSON.

Let’s save that URL into a variable.

url = 'https://xkcd.com/info.0.json'
## Importing libraries

Then we continue with importing Requests library for easily fetching information from the Internet.

import requests

Now we are ready to fetch the data at the URL into a variable.

response = requests.get(url)

Evaluating variables

And we evaluate response and its content into standard output to see what we have.

response
<Response [200]>
response.content
b'{"month": "1", "num": 2250, "link": "", "year": "2020", "news": "", "safe_title": "OK/okay/ok", "transcript": "", "alt": "After changing it back and forth several times and consulting with internet linguist Gretchen McCulloch, I settled on \\"ok\\" in my book How To, but I\'m still on the fence. Maybe I should just switch to \\"oK.\\"", "img": "https://imgs.xkcd.com/comics/ok_okay_ok.png", "title": "OK/okay/ok", "day": "3"}'

That is somewhat readable, but we should do better.

Displaying JSON

One of the many great Jupyter features provided by the underlying IPython foundation, is support for rich output.

In this case, we can use IPython display JSON helper class to let JupyterLab know that it should display JSON.

from IPython.display import JSON

json = response.json()
JSON(json)
<IPython.core.display.JSON object>

In the same way, we can also display the actual strip from the URL provided in JSON.

Displaying images

We fetch the raw data from the image URL, from the JSON data, and render it using IPython display Image helper class.

from IPython.display import Image

url = json['img']
response = requests.get(url)
Image(response.content)
../../_images/02 Python XKCD_21_0.png

Fortunately, because this is popular use-case, it is enough to pass just the URL of the image to the Image helper class and it does also the fetch for us.

Image(url)
../../_images/02 Python XKCD_23_0.png

The XKCD strip from https://xkcd.com/ is licensed under a Creative Commons Attribution-NonCommercial 2.5 License.