Using The Requests Library

What is The requests Library?

Python is “batteries included”, but sometimes the included libraries available in the standard library can be hard to understand. The standard library focuses on functionality, but not necessarily ease of use.

That’s where external libraries come in. The external requests library was developed by Kenneth Reitz to make working with APIs in Python a lot easier. He calls it “HTTP, for humans.” It’s become of the (if not the most) popular Python library!

Our First Request With The requests Library

If you didn’t install the requests library in the working with libraries chapter, you’ll need to do that first before running this code. Use: python -m pip install requests

Let’s make a request to to get ourselves some dog pictures. Create a file called in our pyworkshop directory and copy this:

# First thing we'll do is import the requests library
import requests

# Define a variable with the URL of the API
api_url = ""

# Call the root of the api with GET, store the answer in a response variable
# This call will return a list of URLs that represent dog pictures
response = requests.get(api_url)

# Get the status code for the response. Should be 200 OK
# Which means everything worked as expected
print(f"Response status code is: {response.status_code}")

# Get the result as JSON
response_json = response.json()

# Print it. We should see a list with one image URL.
(env) $ python
Response status code is: 200

Dealing with Errors

When dealing with HTTP requests, your first indication of error is usually the HTTP status code. You saw some of the common status codes in the last chapter. The most common status codes are probably 200 - Success, and 404 - Not found. You can find the status code in the status_code property of the response object:

# Passing in a non-existant URL will result in a 404 (not found)
bad_response = requests.get("")
print(f"Bad Response Status Code is: {bad_response.status_code}")  # Status code is 404, meaning that resource doesn’t exist.

Passing in Parameters

# We'll store our base URL here and pass in the count parameter later
api_url = ""

params = {
   "count": 10

# Pass those params in with the request.
api_response = requests.get(api_url, params=params)

print(f"Shibe API Response Status Code is: {api_response.status_code}")  # should be 200 OK

json_data = api_response.json()

print("Here is a list of URLs for dog pictures:")
for url in json_data:
    print(f"\t {url}")
Shibe API Response Status Code is: 200
Here is a list of URLs for dog pictures:

More about requests

To learn more about the requests library after class, look at the quick start.