Skip to content

Commit 1fff248

Browse files
authored
docs: rpc example for array of json objects
This change adds an explanation of how to handle an array of JSON objects within an RPC call. To pass multiple objects, an array of JSON objects must be the JSON value, with the key being the json or jsonb variable name of the Postgres function. For people who want to perform multiple tasks/inserts/updates within a single API call, this is a needed explanation for that use-case.
1 parent f5264c5 commit 1fff248

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

docs/references/api/functions.rst

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,40 @@ The function parameter names match the JSON object keys in the POST case, for th
7171

7272
.. _function_single_json:
7373

74+
Functions with an array of JSON objects
75+
----------------------------------------------
76+
77+
If you want to pass multiple JSON objects to a Postgres function (an array of objects), you can create a function with a parameter of type ``json`` or ``jsonb``.
78+
79+
Within the curl request, this JSON must be embedded in an object where they key matches the same name as the function's ``json`` or ``jsonb`` parameter.
80+
This will allow you to loop over the array of JSON objects within the Postgres function.
81+
82+
This practice may allow you to reduce the number of ``curl`` requests required to accomplish a task.
83+
84+
For instance, assume we have created this function in the database.
85+
86+
.. code-block:: postgres
87+
88+
CREATE FUNCTION update_data(p_json jsonb)
89+
RETURNS void AS $$
90+
DECLARE
91+
json_item json;
92+
BEGIN
93+
FOR json_item IN SELECT jsonb_array_elements(p_json) LOOP
94+
UPDATE data_table SET data_text_column = (json_item->>'data_text')::text
95+
WHERE data_int_column = (json_item->>'data_int')::integer;
96+
END LOOP;
97+
END;
98+
$$ LANGUAGE SQL IMMUTABLE;
99+
100+
A ``curl`` request using the POST method would look like the following:
101+
102+
.. code-block:: bash
103+
104+
curl "http://localhost:3000/rpc/update_data" \
105+
-X POST -H "Content-Type: application/json" \
106+
-d '{ "p_json": [ { "data_text": "one", "data_int": "1" }, { "data_text": "two", "data_int": "2" } ] }'
107+
74108
Functions with a single unnamed JSON parameter
75109
----------------------------------------------
76110

0 commit comments

Comments
 (0)