Python / Python APIs and RESTful Services
Consuming APIs with Python
A tutorial about Consuming APIs with Python
Section overview
5 resourcesExplores 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
- Write a Python script to get the user details from the JSONPlaceholder API.
- Write a Python script to update a post using the JSONPlaceholder API.
- Write a Python script to delete a post using the JSONPlaceholder API.
Solutions
- 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)
- 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)
- 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.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI 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 articleAI 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 articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article