Skip to content

Consuming APIs with Python: requests

In today’s interconnected world, APIs (Application Programming Interfaces) serve as the backbone for much of the software we use. For IBM i users, leveraging APIs can unlock a wealth of data and functionality, bridging the gap between traditional applications and modern services. This post will introduce you to the basics of consuming APIs using Python on the IBM i platform, complete with a real example that you can try out today.

Why Python for API Consumption?

Python stands out for its simplicity and readability, making it an ideal choice for interacting with web APIs. With its vast standard library and third-party modules, Python simplifies the process of sending requests to a web server and handling the responses. Furthermore, Python’s popularity in the development community means you’re likely to encounter Python example code in API documentation, making it easier to understand and implement API integrations.

One such third-party module is requests, which we will use in this tutorial.

Setting Up Your Environment

Once Python is set up, you’ll need to install the requests library. You can do this by running the following command:

Terminal window
pip3 install requests

API Examples

For this example, we’ll use the is.gd service to shorten a URL. This demonstrates not only how to consume APIs using Python but also gives us a practical utility that can be used in a variety of applications.

Here’s a Python script that takes a URL as input and uses the is.gd service to generate a shortened version of that URL:

shorten_url.py
import requests
def shorten_url(original_url):
api_url = 'https://is.gd/create.php'
params = {
'format': 'json',
'url': original_url
}
response = requests.get(api_url, params=params)
if response.status_code == 200:
short_url = response.json().get('shorturl')
print(f"Original URL: {original_url}")
print(f"Shortened URL: {short_url}")
else:
print('Failed to shorten URL', response.status_code)
if __name__ == "__main__":
# Example URL to shorten
original_url = 'https://example.com'
shorten_url(original_url)

In this script, we construct a GET request to the is.gd API with the original URL passed as a parameter. We specify the format as JSON so that the response is easy to parse. Upon a successful request, the API returns a JSON object from which we extract the shortened URL.

Running the Script on IBM i

Save as shorten_url.py on the IFS then in a terminal or QSH:

Terminal window
python3 shorten_url.py

You should see the original URL and its shortened version printed out to your console.

Why This Matters

URL shortening is a common task in modern web development, useful for making links more manageable, tracking click rates, or simply saving space in documents and messages. Demonstrating API consumption with Python through a practical example like URL shortening showcases the immediate utility and flexibility of Python scripting on IBM i systems.