Skip to Content
Course content

10.1 Making API Requests

In Python, making API requests allows you to interact with external services and retrieve data from them. APIs (Application Programming Interfaces) are essential for integrating third-party systems, such as fetching weather data, interacting with social media platforms, or accessing financial information.

Python provides several libraries for making API requests, but the most commonly used one is requests. This library simplifies the process of sending HTTP requests and handling responses.

1. Installing the requests library

First, if you haven't already installed the requests library, you can do so using pip:

pip install requests

2. Basic API Request: GET Method

The GET method is used to retrieve data from an API. Here’s how you can make a basic GET request to an API using Python.

import requests

# URL of the API endpoint
url = "https://api.example.com/data"

# Making a GET request to the API
response = requests.get(url)

# Check if the request was successful
if response.status_code == 200:
    data = response.json()  # Parse the JSON response
    print(data)  # Print the data
else:
    print("Failed to retrieve data. Status code:", response.status_code)

Explanation:

  • requests.get(url) sends a GET request to the specified URL.
  • response.status_code checks the HTTP status code returned by the API.
  • response.json() parses the JSON content returned by the API into a Python dictionary.

Example Response:

{
    "data": [
        {
            "id": 1,
            "name": "Item 1"
        },
        {
            "id": 2,
            "name": "Item 2"
        }
    ]
}

3. Handling Query Parameters

Often, API requests require parameters (such as filtering data or pagination). You can pass query parameters in the URL or as a dictionary.

import requests

url = "https://api.example.com/data"
params = {
    "page": 1,
    "limit": 10
}

response = requests.get(url, params=params)

if response.status_code == 200:
    data = response.json()
    print(data)
else:
    print("Failed to retrieve data. Status code:", response.status_code)

Here, the parameters page=1 and limit=10 are included in the URL query string.

4. Making POST Requests

POST requests are used to send data to the server, often to create or update resources. Here’s an example of sending a POST request:

import requests

url = "https://api.example.com/data"
data = {
    "name": "New Item",
    "price": 100
}

response = requests.post(url, json=data)

if response.status_code == 201:
    print("Data created successfully!")
    print(response.json())  # Print the response from the server
else:
    print("Failed to create data. Status code:", response.status_code)

Explanation:

  • requests.post(url, json=data) sends a POST request with the data in JSON format to the server.
  • If the request is successful, the status code 201 is often returned (indicating that the resource was created).

5. Adding Headers to the Request

In some cases, APIs require headers, such as authentication tokens or content types. You can include headers in your request like this:

import requests

url = "https://api.example.com/data"
headers = {
    "Authorization": "Bearer YOUR_ACCESS_TOKEN",
    "Content-Type": "application/json"
}

response = requests.get(url, headers=headers)

if response.status_code == 200:
    data = response.json()
    print(data)
else:
    print("Failed to retrieve data. Status code:", response.status_code)

Here, the Authorization header is used to send a bearer token (commonly used for OAuth-based authentication), and the Content-Type header specifies the format of the request body.

6. Error Handling in API Requests

While making API requests, you should always handle potential errors (such as timeouts, connection issues, or non-200 status codes). Here's how you can do that:

import requests
from requests.exceptions import Timeout, RequestException

url = "https://api.example.com/data"

try:
    response = requests.get(url, timeout=10)  # 10 seconds timeout
    response.raise_for_status()  # Raise an exception for HTTP error responses (non-2xx)
    data = response.json()
    print(data)

except Timeout:
    print("The request timed out.")
except RequestException as e:
    print(f"An error occurred: {e}")

In this example:

  • The timeout parameter ensures that the request will raise an error if the server does not respond within the specified time.
  • response.raise_for_status() raises an exception for HTTP error status codes (e.g., 404 or 500).

7. Handling JSON Responses

Many APIs return data in JSON format, which you can easily parse using the .json() method.

import requests

url = "https://api.example.com/data"
response = requests.get(url)

if response.status_code == 200:
    data = response.json()  # Automatically parse JSON into a Python dictionary
    print(data)
else:
    print("Request failed with status code:", response.status_code)

Once the data is converted into a Python dictionary, you can access it like any other dictionary.

8. Making Asynchronous API Requests

If you need to make multiple API requests in parallel (to save time), you can use the aiohttp library to send asynchronous requests.

Install aiohttp:

pip install aiohttp

Example of asynchronous requests:

import aiohttp
import asyncio

async def fetch_data(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()

async def main():
    url = "https://api.example.com/data"
    data = await fetch_data(url)
    print(data)

asyncio.run(main())

This approach uses the asyncio module to send the request asynchronously and is useful for making concurrent requests without blocking your program.

Summary of Key Points:

  • GET requests: Used to retrieve data from an API.
  • POST requests: Used to send data to an API (e.g., creating or updating resources).
  • Query parameters: Can be added to URLs to pass information to the API.
  • Headers: Used to send additional information, such as authentication tokens.
  • Error handling: Should be implemented to deal with timeouts, request errors, or unsuccessful HTTP responses.
  • JSON: The most common format for API responses; Python’s requests library makes it easy to parse.
  • Asynchronous requests: Using libraries like aiohttp, you can make requests asynchronously for efficiency when handling multiple requests simultaneously.

By mastering these concepts, you will be able to interact with various APIs and retrieve, send, and process data efficiently using Python.

Commenting is not enabled on this course.