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
6 changes: 5 additions & 1 deletion piccolo_api/crud/endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -982,7 +982,11 @@ async def post_single(
request=request,
)
response = await row.save().run()
json = dump_json(response)
# `save()` on a new row inserts it and returns a list with
# a single item (the primary key of the inserted row) - we
# only ever insert one row here, so unwrap it into a plain
# object instead of returning a single-item list.
json = dump_json(response[0])
# Returns the id of the inserted row.
return CustomJSONResponse(json, status_code=201)
except ValueError:
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