Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions piccolo_api/crud/endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -982,8 +982,8 @@ async def post_single(
request=request,
)
response = await row.save().run()
json = dump_json(response)
# Returns the id of the inserted row.
# save() returns a single-item list - unwrap it.
json = dump_json(response[0])
return CustomJSONResponse(json, status_code=201)
except ValueError:
return Response(
Expand Down
19 changes: 19 additions & 0 deletions tests/crud/test_crud_endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -1357,6 +1357,25 @@ def test_success(self):
self.assertEqual(movie.name, json["name"])
self.assertEqual(movie.rating, json["rating"])

def test_response_body_is_a_dict_not_a_list(self):
"""
The response body should be a JSON object (e.g. ``{"id": 1}``), not
a single-item list (e.g. ``[{"id": 1}]``), so a client can read the
id straight off the parsed response without unwrapping a list.

https://github.com/piccolo-orm/piccolo_api/issues/211
"""
client = TestClient(PiccoloCRUD(table=Movie, read_only=False))

response = client.post("/", json={"name": "Star Wars", "rating": 93})
self.assertEqual(response.status_code, 201)

body = response.json()
self.assertIsInstance(body, dict)

movie = Movie.objects().first().run_sync()
self.assertEqual(body["id"], movie.id)

def test_post_user_success(self):
client = TestClient(PiccoloCRUD(table=BaseUser, read_only=False))

Expand Down
2 changes: 1 addition & 1 deletion tests/fastapi/test_fastapi_endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ def test_post(self):
"/movies/", json={"name": "Star Wars", "rating": 93}
)
self.assertEqual(response.status_code, 201)
self.assertEqual(response.json(), [{"id": 2}])
self.assertEqual(response.json(), {"id": 2})

def test_put(self):
client = TestClient(app)
Expand Down