Simplifying REST API Requests in Python with a Generic Function

Emanuele
2 min readJan 9, 2024

--

In the world of Python development, making HTTP requests to REST APIs is a common task. Whether you’re retrieving data, sending updates, or interacting with third-party services, a reusable function can significantly streamline your workflow. In this article, we’ll explore a generic function for making REST API requests that is not only concise but also versatile.

Writing boilerplate code for each API request can be cumbersome and prone to inconsistencies. As developers, we often find ourselves repeating similar patterns when dealing with different endpoints. What if there was a way to encapsulate this logic into a single, reusable function?

import requests
import logging

def rest_api(url, method='get', return_type='json', **kwargs):
"""
Generic function to make a REST API request.

:param url: The URL of the API endpoint.
:param method: The HTTP method ('get' by default).
:param return_type: The expected return type ('json' or 'object' by default).
:param **kwargs: Additional keyword arguments to be passed to the requests library.
:return: JSON response or the response object.
"""
try:
response = requests.request(method, url, **kwargs)
response.raise_for_status() # Raise an exception for non-2xx status codes
except requests.exceptions.RequestException as e:
logging.error(f"API request failed: {e}")
return None # Return None to indicate failure

if return_type == 'json':
return response.json()
elif return_type == 'object':
return response

All the details of the method request are available in the official documentation:
https://requests.readthedocs.io/en/latest/api/

Example usage

# Example usage of the rest_api function
url = 'https://api.example.com'
headers = {'Authorization': 'Bearer YOUR_ACCESS_TOKEN'}
params = {'param1': 'value1', 'param2': 'value2'}
data = {'key': 'value'}
method = 'post'
return_type = 'json'

# JSON response
response_json = rest_api(url, method=method,\
headers=headers, params=params, data=data, return_type='json')

# Raw response object
response_object= rest_api(url, method=method,\
headers=headers, params=params, data=data, return_type='object')

This example demonstrates the ease of making API requests using the rest_api function. By providing the necessary parameters, developers can focus on their specific use case without getting bogged down by repetitive code.

This function does not cover every scenario. If you require a different type of authorization, this code may need an update, but it can serve as a good starting point.

Feel free to incorporate this function into your projects and customize it based on your specific needs. The goal is to make API interactions a seamless part of your Python development journey.
Happy coding! 🚀

--

--

Emanuele

LA-based robotics engineer specializing in Azure technologies. Passionate about system design, AI, and entrepreneurship, dedicated to driving tech innovation