Python / Python APIs and RESTful Services

Consuming APIs with Python

A tutorial about Consuming APIs with Python

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Explores how to create and consume RESTful APIs using Python.

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')

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

Time Zone Converter

Convert time between different time zones.

Use tool

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

Image Converter

Convert between different image formats.

Use tool

Color Palette Generator

Generate color palettes from images.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help