Skip to content

Commit 1974f70

Browse files
feat(min-demo): add shared json request parsing helper
1 parent 12b8d62 commit 1974f70

2 files changed

Lines changed: 22 additions & 12 deletions

File tree

server/cities_endpoints.py

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
validate_pagination,
1010
validate_range_filters,
1111
)
12+
from server.request_parsing import get_json_object_or_abort
1213

1314
cities_ns = Namespace('cities', description='City operations')
1415

@@ -128,16 +129,6 @@
128129
})
129130

130131

131-
def _get_json_body() -> dict:
132-
payload = request.get_json(silent=True)
133-
if payload is None or not isinstance(payload, dict):
134-
cities_ns.abort(
135-
HTTPStatus.BAD_REQUEST,
136-
'Request body must be a valid JSON object',
137-
)
138-
return payload
139-
140-
141132
@cities_ns.route('')
142133
class CitiesList(Resource):
143134

@@ -192,7 +183,7 @@ def post(self):
192183
Creates a new city with the provided data.
193184
Timestamps are automatically set by the server.
194185
"""
195-
city_data = _get_json_body()
186+
city_data = get_json_object_or_abort(request, cities_ns.abort)
196187

197188
state_code = city_data.get('state_code')
198189
country_code = city_data.get('country_code')
@@ -314,7 +305,7 @@ def put(self, state_code, city_name):
314305
Updates the city with the provided data.
315306
The updated_at timestamp is automatically set by the server.
316307
"""
317-
update_data = _get_json_body()
308+
update_data = get_json_object_or_abort(request, cities_ns.abort)
318309

319310
try:
320311
success = cities_data.update_city(

server/request_parsing.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
"""Helpers for parsing and validating JSON request bodies."""
2+
3+
from http import HTTPStatus
4+
from typing import Any, Callable
5+
6+
from flask import Request
7+
8+
AbortFunc = Callable[[HTTPStatus, str], None]
9+
10+
11+
def get_json_object_or_abort(request: Request, abort_func: AbortFunc) -> dict[str, Any]:
12+
"""Return a JSON object payload or abort with a consistent 400 error."""
13+
payload = request.get_json(silent=True)
14+
if payload is None or not isinstance(payload, dict):
15+
abort_func(
16+
HTTPStatus.BAD_REQUEST,
17+
'Request body must be a valid JSON object',
18+
)
19+
return payload

0 commit comments

Comments
 (0)