PostgreSQL
Last updated
Was this helpful?
Was this helpful?
CREATE OR REPLACE FUNCTION py_pgrest(p_url text, p_method text DEFAULT 'POST'::text, p_data text DEFAULT ''::text, p_headers text DEFAULT '{"Content-Type": "application/json"}'::text)
RETURNS text
LANGUAGE plpython3u
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$
;select json_build_object( 'data', json_agg(json_build_object( 'promoCode' , promoCode , 'productType', productType, 'period', period)) )
into body
from (select * from my_dr_input dr OFFSET lastBatchStart - 1 FETCH FIRST batchSize rows only); py_pgrest( 'https://api.decisionrules.io/rule/solve/' || rule_alias,
'POST' ,
body,
'{"Authorization":"Bearer ' || API_KEY || '","Content-Type": "application/json"}');result = py_pgrest( 'https://api.decisionrules.io/rule/solve/' || rule_alias,
'POST' ,
body,
'{"Authorization":"Bearer ' || API_KEY || '","Content-Type": "application/json"}');
-- store results in a table
-- use -> to access nested object
-- use ->> to extract the value
-- use ::data_type to convert the value into your desired datatype
insert into results
select (res::json->'prices'->>'finalPrice')::float ,
(res::json->'prices'->>'crudePrice')::float ,
res::json->>'message'
-- parse the response by object
from (select JSON_ARRAY_ELEMENTS(JSON_ARRAY_ELEMENTS(result::json) ) as res ) ;[ [result1...resultN], [result1..resultM] , ... ]