146. Interfacing with RESTful APIs using requests

Interfacing with RESTful APIs using Python's requests module is a common task for sending HTTP requests and handling responses. Here are some basic and advanced examples demonstrating how to interact with RESTful APIs using requests.

1. Making a GET Request

A simple GET request to retrieve data from an API.

Copy

import requests

def get_data_from_api(url):
    response = requests.get(url)
    if response.status_code == 200:
        print("Data retrieved successfully:")
        print(response.json())  # Assuming the response is in JSON format
    else:
        print(f"Failed to retrieve data. Status code: {response.status_code}")

# Example usage
get_data_from_api('https://jsonplaceholder.typicode.com/posts')

Explanation:

  • requests.get(url) sends a GET request to the provided URL.

  • response.json() parses the JSON response into a Python dictionary.

2. Making a POST Request

Sending data to an API using a POST request.

Copy

Explanation:

  • requests.post(url, json=data) sends a POST request with JSON data.

  • response.status_code == 201 checks if the data was successfully created.

3. Handling Query Parameters in GET Requests

Sending query parameters with a GET request.

Copy

Explanation:

  • The params argument in requests.get(url, params=params) adds query parameters to the URL.

  • For example, https://jsonplaceholder.typicode.com/posts?userId=1.

4. Handling Headers in Requests

Customizing headers in your HTTP requests.

Copy

Explanation:

  • The headers argument in requests.get(url, headers=headers) allows you to send custom headers, such as authorization tokens.

5. Making PUT Requests to Update Data

Sending data to update an existing resource using a PUT request.

Copy

Explanation:

  • requests.put(url, json=data) sends a PUT request to update an existing resource at the given URL.

6. Making DELETE Requests

Deleting a resource with a DELETE request.

Copy

Explanation:

  • requests.delete(url) sends a DELETE request to the specified URL to remove a resource.

7. Handling Timeouts in Requests

Setting a timeout for your HTTP requests to avoid waiting indefinitely.

Copy

Explanation:

  • The timeout parameter in requests.get(url, timeout=timeout) specifies how many seconds to wait before raising a Timeout exception.

8. Handling JSON Response

Parsing a JSON response and handling potential errors.

Copy

Explanation:

  • response.raise_for_status() raises an exception if the HTTP request returned an error (status code >= 400).

  • response.json() parses the JSON response.

9. Handling Response Status Codes

Checking the status code to handle different API responses.

Copy

Explanation:

  • Different status codes (e.g., 404 for "Not Found", 500 for "Internal Server Error") are handled using conditional checks.

10. Sending Form Data with POST Requests

Sending form data using requests.post().

Copy

Explanation:

  • data=form_data sends form-encoded data in a POST request.


Conclusion:

The requests library in Python makes interacting with RESTful APIs straightforward. You can handle GET, POST, PUT, DELETE requests, work with query parameters, headers, timeouts, and responses easily. Whether you're interacting with JSON, form data, or handling different HTTP status codes, the requests module provides all the necessary tools to handle API interactions effectively.

Last updated