Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

A function in PostgreSQL can be used to access a REST API by using the PL/Python language. PL/Python supports the use of HTTP requests and can be used to interact with REST APIs.

Here is an example of a function that uses the requests library to make a GET request to a REST API:

CREATE OR REPLACE FUNCTION get_api_data(url TEXT)
RETURNS JSON
LANGUAGE plpythonu
AS $$
import requests

response = requests.get(url)
if response.status_code == 200:
    return response.json()
else:
    raise Exception("Failed to get data from the API")
$$;

This function takes a URL as input and returns the JSON response from the API. To use this function, simply call it with the appropriate URL:

SELECT get_api_data('https://api.example.com/data');

Note that you will need to have the requests library installed in your PostgreSQL environment for this function to work. Additionally, be sure to carefully test any functions that interact with external APIs to ensure they behave as expected and handle errors gracefully.