Certainly! Here’s a generic Python function to handle REST API calls using the popular requests library. This function supports different HTTP methods, headers, query parameters, request bodies, and error handling.
import requests
def call_rest_api(
url,
method='GET',
headers=None,
params=None,
data=None,
json=None,
timeout=10,
**kwargs
):
"""
Generic function to call a REST API.
Args:
url (str): The API endpoint.
method (str): HTTP method ('GET', 'POST', 'PUT', 'DELETE', etc.).
headers (dict): HTTP headers.
params (dict): URL query parameters.
data (dict or str): Data to send in the body (for POST/PUT).
json (dict): JSON data to send in the body (for POST/PUT).
timeout (int or float): Timeout in seconds.
**kwargs: Additional arguments for requests.request.
Returns:
requests.Response: The response object.
Raises:
requests.RequestException: For network-related errors.
requests.HTTPError: For bad HTTP responses (status code >= 400).
"""
try:
response = requests.request(
method=method,
url=url,
headers=headers,
params=params,
data=data,
json=json,
timeout=timeout,
**kwargs
)
response.raise_for_status() # Raises HTTPError for bad responses (4xx, 5xx)
return response
except requests.RequestException as e:
print(f"Error calling API: {e}")
raise
# Example usage:
# response = call_rest_api(
# url="https://jsonplaceholder.typicode.com/posts",
# method="GET"
# )
# print(response.json())
Notes:
- You can pass any HTTP method (
GET, POST, PUT, DELETE, etc.).
- Use
params for query parameters, data for form data, and json for JSON payloads.
- Additional arguments (like
auth, files, etc.) can be passed via **kwargs.
- The function raises exceptions for network errors and HTTP errors (status code >= 400).
Let me know if you need a version with async support or more customization!