Consuming APIs with Python

Tutorial 3 of 5

Introduction

In this tutorial, we will learn how to consume APIs (Application Programming Interfaces) using Python. APIs are a way for different software applications to communicate with each other. They expose a specific set of functions and/or data for other software to use. By consuming APIs, you can extend the functionality of your own applications, or build new applications which rely on data and services provided by other applications.

By the end of this tutorial, you will be able to:
- Understand what an API is and how it works
- Use Python's requests module to send HTTP requests to an API
- Parse and use the data returned by an API

Prerequisites for this tutorial include a basic understanding of Python programming, and familiarity with the concept of HTTP requests (GET, POST, etc.).

Step-by-Step Guide

We will use the requests module in Python to send HTTP requests to an API. This module abstracts the complexities of making requests behind a simple API, allowing you to send HTTP/1.1 requests.

Installing the Requests Module

Before we begin, you need to install the requests module. You can install it using pip:

pip install requests

Making a GET Request

Making a GET request is as simple as:

import requests

response = requests.get('https://jsonplaceholder.typicode.com/posts')

# This will print the status code
print(response.status_code)

Handling the Response

The response of an API request is usually in JSON format. The requests module automatically decodes the JSON for you:

import requests

response = requests.get('https://jsonplaceholder.typicode.com/posts')

# This will print the entire JSON response
print(response.json())

Code Examples

Let's examine a few examples of consuming APIs with Python.

Example 1: Getting Data from an API

import requests

# Send a GET request to the API
response = requests.get('https://jsonplaceholder.typicode.com/posts')

# Check if the request was successful
if response.status_code == 200:

    # Get the JSON data from the response
    data = response.json()

    # Print each post in the data
    for post in data:
        print(post['title'])

Example 2: Sending Data to an API

import requests
import json

# Data to send
data = {'title': 'foo', 'body': 'bar', 'userId': 1}

# Send a POST request to the API
response = requests.post('https://jsonplaceholder.typicode.com/posts', data=json.dumps(data))

# Check if the request was successful
if response.status_code == 201:

    # Get the JSON data from the response
    data = response.json()

    # Print the data
    print(data)

Summary

In this tutorial, we learned how to consume APIs with Python using the requests module. We learned how to send GET and POST requests, and how to handle the response from an API.

For further learning, you can look into other types of HTTP requests like PUT and DELETE. You can also learn about handling errors and exceptions when making API requests.

Practice Exercises

  1. Write a Python script to get the user details from the JSONPlaceholder API.
  2. Write a Python script to update a post using the JSONPlaceholder API.
  3. Write a Python script to delete a post using the JSONPlaceholder API.

Solutions

  1. To get user details:
import requests

# Send a GET request to the API
response = requests.get('https://jsonplaceholder.typicode.com/users/1')

# Check if the request was successful
if response.status_code == 200:

    # Get the JSON data from the response
    data = response.json()

    # Print the data
    print(data)
  1. To update a post:
import requests
import json

# Data to send
data = {'id': 1, 'title': 'foo', 'body': 'bar', 'userId': 1}

# Send a PUT request to the API
response = requests.put('https://jsonplaceholder.typicode.com/posts/1', data=json.dumps(data))

# Check if the request was successful
if response.status_code == 200:

    # Get the JSON data from the response
    data = response.json()

    # Print the data
    print(data)
  1. To delete a post:
import requests

# Send a DELETE request to the API
response = requests.delete('https://jsonplaceholder.typicode.com/posts/1')

# Check if the request was successful
if response.status_code == 200:

    # Print a success message
    print('Post deleted successfully')