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.
import requests
def send_data_to_api(url, data):
response = requests.post(url, json=data)
if response.status_code == 201:
print("Data posted successfully.")
print(response.json()) # Assuming the response is in JSON format
else:
print(f"Failed to post data. Status code: {response.status_code}")
# Example usage
data = {'title': 'foo', 'body': 'bar', 'userId': 1}
send_data_to_api('https://jsonplaceholder.typicode.com/posts', data)
import requests
def get_data_with_params(url, params):
response = requests.get(url, params=params)
if response.status_code == 200:
print("Data retrieved successfully:")
print(response.json())
else:
print(f"Failed to retrieve data. Status code: {response.status_code}")
# Example usage
params = {'userId': 1}
get_data_with_params('https://jsonplaceholder.typicode.com/posts', params)
import requests
def get_data_with_headers(url, headers):
response = requests.get(url, headers=headers)
if response.status_code == 200:
print("Data retrieved successfully:")
print(response.json())
else:
print(f"Failed to retrieve data. Status code: {response.status_code}")
# Example usage
headers = {'Authorization': 'Bearer your_token_here'}
get_data_with_headers('https://jsonplaceholder.typicode.com/posts', headers)
import requests
def update_data_in_api(url, data):
response = requests.put(url, json=data)
if response.status_code == 200:
print("Data updated successfully.")
print(response.json())
else:
print(f"Failed to update data. Status code: {response.status_code}")
# Example usage
data = {'id': 1, 'title': 'updated title', 'body': 'updated body'}
update_data_in_api('https://jsonplaceholder.typicode.com/posts/1', data)
import requests
def delete_data_from_api(url):
response = requests.delete(url)
if response.status_code == 200:
print("Data deleted successfully.")
else:
print(f"Failed to delete data. Status code: {response.status_code}")
# Example usage
delete_data_from_api('https://jsonplaceholder.typicode.com/posts/1')
import requests
def get_data_with_timeout(url, timeout):
try:
response = requests.get(url, timeout=timeout)
if response.status_code == 200:
print("Data retrieved successfully:")
print(response.json())
else:
print(f"Failed to retrieve data. Status code: {response.status_code}")
except requests.Timeout:
print("The request timed out.")
except requests.RequestException as e:
print(f"An error occurred: {e}")
# Example usage
get_data_with_timeout('https://jsonplaceholder.typicode.com/posts', timeout=5)
import requests
def fetch_json_data(url):
response = requests.get(url)
try:
response.raise_for_status() # Raise HTTPError for bad responses
data = response.json()
print("JSON data:", data)
except requests.exceptions.HTTPError as err:
print(f"HTTP error occurred: {err}")
except ValueError:
print("Error parsing JSON response")
# Example usage
fetch_json_data('https://jsonplaceholder.typicode.com/posts')
import requests
def handle_status_code(url):
response = requests.get(url)
if response.status_code == 200:
print("Success!")
elif response.status_code == 404:
print("Resource not found.")
elif response.status_code == 500:
print("Server error occurred.")
else:
print(f"Unexpected status code: {response.status_code}")
# Example usage
handle_status_code('https://jsonplaceholder.typicode.com/posts/1')
import requests
def send_form_data(url, form_data):
response = requests.post(url, data=form_data)
if response.status_code == 200:
print("Form submitted successfully.")
print(response.text)
else:
print(f"Failed to submit form. Status code: {response.status_code}")
# Example usage
form_data = {'username': 'john_doe', 'password': 'secret'}
send_form_data('https://httpbin.org/post', form_data)