Using plpython2u language:
Solution 1: (using urllib2)
CREATE OR REPLACE FUNCTION public.py_pgrest(uri text, body text DEFAULT NULL::text, content_type text DEFAULT 'application/json'::text)
RETURNS text
LANGUAGE plpython2u
AS $function$
import urllib2
from urllib2 import Request, urlopen, URLError, HTTPError
req = Request(uri)
if body:
req.add_data(body)
if content_type:
req.add_header('Content-Type', content_type)
try:
data = urlopen(req)
except HTTPError as e:
return e
except URLError as e:
if hasattr(e, 'reason'):
return e.reason
elif hasattr(e, 'code'):
return e.code
else:
return e
else:
return data.read()
$function$
;
Solution 2: (using requests)
CREATE OR REPLACE FUNCTION public.py_pgrest(p_url text, p_method text DEFAULT 'GET'::text, p_data text DEFAULT ''::text, p_headers text DEFAULT '{"Content-Type": "application/json"}'::text)
RETURNS text
LANGUAGE plpython2u
AS $function$
import requests, json
try:
r = requests.request(method=p_method, url=p_url, data=p_data, headers=json.loads(p_headers))
except Exception as e:
return e
else:
return r.content
$function$
;