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.
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 aGETrequest 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.
Explanation:
requests.post(url, json=data)sends aPOSTrequest with JSON data.response.status_code == 201checks if the data was successfully created.
3. Handling Query Parameters in GET Requests
Sending query parameters with a GET request.
Explanation:
The
paramsargument inrequests.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.
Explanation:
The
headersargument inrequests.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.
Explanation:
requests.put(url, json=data)sends aPUTrequest to update an existing resource at the given URL.
6. Making DELETE Requests
Deleting a resource with a DELETE request.
Explanation:
requests.delete(url)sends aDELETErequest to the specified URL to remove a resource.
7. Handling Timeouts in Requests
Setting a timeout for your HTTP requests to avoid waiting indefinitely.
Explanation:
The
timeoutparameter inrequests.get(url, timeout=timeout)specifies how many seconds to wait before raising aTimeoutexception.
8. Handling JSON Response
Parsing a JSON response and handling potential errors.
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.
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().
Explanation:
data=form_datasends form-encoded data in aPOSTrequest.
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