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?
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
.