1

I'm trying to make a client for postgREST (latest version with PostgreSQL 13)

When I tried to insert data, I felt on (what seems to me) a strange behavior: when I use json.dumps for an insert request, event if my value are wrong, I get a 201 code in response.

Working code
The field id is a primary key.

headers["Authorization"] = mytoken
myjson = {"id": "13", "name":"nameinserted"}
r = requests.post(url, json=myjson, headers=headers)

Returns a 201 code If I retry that code, I get a 409 (which is normal)

Not working code :
This one always returns me a 201 code, and never insert something in database (even with correct data). The difference is json.dumps(myjson) that I used by mistake.

headers["Authorization"] = mytoken
myjson = {"id": "13", "name":"nameinserted"}
myjson = json.dumps(myjson)
r = requests.post(url, json=myjson, headers=headers)

Why don't I get an error about data or malformed json?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
OldPoorDev
  • 13
  • 1
  • 5

1 Answers1

0

In the first example you gave, the JSON encoded payload sent to PostgREST is:

'{"id": "13", "name": "nameinserted"}'

In the second example, after encoding it once again, the payload sent is:

'"{\\"id\\": \\"13\\", \\"name\\": \\"nameinserted\\"}"'

PostgREST parses the first payload as a JSON value; on the other hand, the second payload is parsed as a String value, equivalent to '"any_string"' for example. PostgREST is lenient with this type of payload and doesn't give an error but defaults it to an empty JSON array '[]', which is allowed even if the array is empty due to bulk insertion, and responds with a 201.

Laurence Isla
  • 343
  • 1
  • 5
  • Thank you for your answer. So PostgREST should return 201 with wrong data in a bulk insertion too ? (sorry I don't understand Haskell). – OldPoorDev Nov 04 '21 at 01:01
  • @Fanch The Haskell code basically says that If the data is not an array or an object then treat it as an empty array (in this case a String is treated as an empty array). In regards to the bulk insert, if the data you send has the same format as the second example in the answer, then yes, it will return a 201. – Laurence Isla Nov 10 '21 at 01:05