fbpx

Consuming and interacting with APIs

Consuming and interacting with APIs involves making HTTP requests to retrieve data from external services or send data to those services. In Python, the requests library is commonly used for this purpose. Below, I’ll provide a step-by-step guide on how to consume and interact with APIs using Python.

1. Installing the requests Library:

Before you start, make sure you have the requests library installed. If not, install it using:

pip install requests

2. Making a GET Request:

To make a GET request and retrieve data from an API:

import requests

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

if response.status_code == 200:
    data = response.json()
    print(data)
else:
    print('Error:', response.status_code)

3. Passing Parameters:

You can pass parameters in the URL for GET requests.

import requests

url = 'https://api.example.com/search'
params = {'query': 'python', 'limit': 10}

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

if response.status_code == 200:
    data = response.json()
    print(data)
else:
    print('Error:', response.status_code)

4. Handling Authentication:

For APIs that require authentication, you can pass credentials using headers.

import requests

url = 'https://api.example.com/data'
headers = {'Authorization': 'Bearer YOUR_ACCESS_TOKEN'}

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

if response.status_code == 200:
    data = response.json()
    print(data)
else:
    print('Error:', response.status_code)

5. Making POST Requests:

To send data to an API using a POST request:

import requests

url = 'https://api.example.com/create'
data = {'name': 'John', 'age': 25}

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

if response.status_code == 201:
    print('Data created successfully!')
else:
    print('Error:', response.status_code)

6. Handling Response Data:

Once you receive the response, you can extract and manipulate the data.

import requests

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

if response.status_code == 200:
    data = response.json()

    # Accessing specific data
    print('Name:', data['name'])
    print('Age:', data['age'])
else:
    print('Error:', response.status_code)

7. Dealing with Rate Limits:

Some APIs impose rate limits. You need to handle these limits to avoid being blocked.

import requests
import time

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

for _ in range(5):
    response = requests.get(url)

    if response.status_code == 200:
        data = response.json()
        print(data)
    elif response.status_code == 429:  # Rate limit exceeded
        print('Rate limit exceeded. Waiting...')
        time.sleep(60)  # Wait for 60 seconds
    else:
        print('Error:', response.status_code)

8. Handling Errors:

Always check the status code and handle errors gracefully.

import requests

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

if response.status_code == 200:
    data = response.json()
    print(data)
elif response.status_code == 404:
    print('Resource not found')
else:
    print('Error:', response.status_code)

These examples provide a foundation for consuming and interacting with APIs in Python. Remember to review the API documentation to understand the available endpoints, required parameters, and any specific authentication methods. The requests library is versatile and can be adapted to various API scenarios.