Ask Your Question
3

How can a function in PostgreSQL be used to access a REST API?

asked 2023-05-11 08:49:35 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-05-11 09:15:02 +0000

ladyg gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-11 08:49:35 +0000

Seen: 18 times

Last updated: May 11 '23