The preceding snippet should be straightforward. We declare a dictionary of URLs against which we want to perform HTTP requests. We have encapsulated the code that performs the request into theget_content()function. As you can see, we perform a GET request (by usingrequests.get()), and we print the title and the JSON decoded version of the body of the response. Let us spend a few words on this last bit.
When we perform a request to a website, or to an API, we get back a response object encapsulating the data that was returned by the server we performed the request against. The body of some responses fromhttpbin.orghappens to be JSON encoded, so instead of getting the body as it is (by readingresp.text) and manually decoding it callingjson.loads()on it, we simply combine the two by leveraging thejson()method of the response object. There are plenty of reasons why therequestspackage has become so widely adopted, and one of them is its ease of use.
Now, when you perform a request in your application, you will want to have a much more robust approach in dealing with errors and so on, but for this chapter, a simple example will do. We will see more examples of requests inChapter 14, Introduction to API Development.
Going back to our code, in the end, we run aforloop and get all the URLs. When you run it, you will see the result of each call printed on your console, which should look like this (prettified and trimmed for brevity):