-
Notifications
You must be signed in to change notification settings - Fork 4
Deploy PostgREST stored procedures with curl
This post is an appendix for PostgREST API Guide/stored-procedures. Step-by-step:
Run at psql
or similar:
CREATE FUNCTION add_them(a integer, b integer) RETURNS integer AS $$
SELECT a + b;
$$ LANGUAGE SQL IMMUTABLE STRICT;
CREATE FUNCTION add_them2(a integer, b integer) -- idem but not IMMUTABLE
RETURNS integer AS $$
SELECT a + b;
$$ LANGUAGE SQL;
CREATE FUNCTION add_them3(integer,integer) -- idem but without parameter names
RETURNS integer AS $$
SELECT $1 + $2;
$$ LANGUAGE SQL IMMUTABLE STRICT;
CREATE FUNCTION add_them_json(p JSON) -- idem but JSON parameter
RETURNS integer AS $$
SELECT ($1->>'a')::int + ($1->>'b')::int;
$$ LANGUAGE SQL IMMUTABLE STRICT;
CREATE FUNCTION add_them_jsonb(p JSONb) -- idem but JSONb parameter
RETURNS integer AS $$
SELECT ($1->>'a')::int + ($1->>'b')::int;
$$ LANGUAGE SQL IMMUTABLE STRICT;
CREATE FUNCTION mult_them(param json) RETURNS int AS $$
SELECT (param->>'x')::int * (param->>'y')::int
$$ LANGUAGE SQL IMMUTABLE STRICT;
Test by SQL:
SELECT add_them(1,2); -- returns 3
SELECT add_them2(1,2); -- returns 3
SELECT add_them3(1,2); -- returns 3
SELECT add_them_json('{"a":1,"b":2}'); -- returns 3
SELECT mult_them('{"x":2,"y":3}'); -- returns 6
Run at server (by ssh
or similar)
- for dockered PostgREST
- Use
docker kill --signal=HUP <container id or name>
to reload. Or just restart the container.
- Use
- for commom PostgREST, schema reloading:
killall -SIGUSR1 postgrest
Use -i
to see headers.
-
curl "http://localhost:3000/rpc/add_them?a=1&b=2"
returns3
. -
curl -H "Content-Type: application/json" --request POST --data '{"a": 1, "b": 2}' http://localhost:3000/rpc/add_them
returns3
. Same as:
curl -i -H "Accept application/json" -H "Accept-Charset: utf-8" -H "Content-Type: application/json" --request POST --data '{"a": 1, "b": 2}' http://localhost:3000/rpc/add_them
-
curl "http://localhost:3000/rpc/add_them2?a=1&b=2"
returns3
. -
curl "http://localhost:3000/rpc/add_them3?a=1&b=2"
returns ERROR 42883. -
curl "http://localhost:3000/rpc/add_them_json?a=1&b=2"
returns ERROR 42883. -
curl -H "Content-Type: application/json" --request POST --data '{"a": 1, "b": 2}' http://localhost:3000/rpc/add_them_json"
returns ERROR 42883. -
curl "http://localhost:3000/rpc/add_them_jsonb?a=1&b=2"
returns ERROR 42883. -
error
curl -H "Content-Type: application/json" --request POST --data '{"x":2,"y":3}' "http://localhost:3000/rpc/mult_them"
-
success!
curl -H "Content-Type: application/json" -H "Prefer: params=single-object" --request POST --data '{"x":2,"y":3}' "http://localhost:3000/rpc/mult_them"
returns 6!