129. Accessing APIs with requests

The requests library in Python simplifies the process of sending HTTP requests and handling responses. It supports various HTTP methods like GET, POST, PUT, DELETE, and more. Below are some code snippets demonstrating how to access APIs, send requests, and handle responses using the requests library.

1. Basic GET Request

A simple GET request to fetch data from an API.

import requests

# Make a GET request to an API
response = requests.get("https://api.github.com")

# Check if the request was successful
if response.status_code == 200:
    print("Response Status Code:", response.status_code)
    print("Response Body:", response.json())  # Get the response as JSON
else:
    print(f"Failed to retrieve data. Status code: {response.status_code}")

2. GET Request with Query Parameters

Adding query parameters to a GET request.

import requests

# Define the API endpoint and parameters
url = "https://api.openweathermap.org/data/2.5/weather"
params = {
    'q': 'London',
    'appid': 'your_api_key_here'  # Replace with your actual API key
}

# Make a GET request with parameters
response = requests.get(url, params=params)

# Check if the request was successful
if response.status_code == 200:
    print("Weather data:", response.json())
else:
    print("Failed to retrieve weather data:", response.status_code)

3. POST Request

Sending data with a POST request to an API.


4. Handling Response JSON

Accessing and processing JSON data from a response.


5. Error Handling in Requests

Handling different HTTP status codes and errors.


6. Sending Headers with Requests

Adding custom headers to a request.


7. Handling Cookies in Requests

Sending and receiving cookies with requests.


8. Timeouts in Requests

Setting a timeout for requests to avoid long waits.


9. File Upload with Requests

Uploading a file using a POST request.


10. Session Object for Persistent Connections

Using a session object to persist certain parameters across multiple requests.


Summary of Key Points:

  • GET: To fetch data from an API.

  • POST: To send data to an API.

  • Error Handling: Use try-except to manage errors and unexpected responses.

  • Headers: Add custom headers to requests.

  • Cookies: Manage cookies with cookies argument in requests.

  • Timeouts: Set timeouts for requests using the timeout parameter.

  • Session: Use requests.Session() to maintain persistent connections.

  • File Upload: Upload files using the files argument in POST requests.

These examples cover basic usage, error handling, authentication, and working with cookies and sessions, providing a comprehensive guide to interacting with APIs using the requests library.

Last updated