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
7 changes: 6 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
## 1.4.2 (unreleased)
---------------------

- Nothing changed yet.
- Fix duplicated Content-Type header in JSON:API responses.
- `BaseJsonApiResponse.base_header` was replaced by `content_type`. A Content-Type header supplied by the
caller is now overridden by the JSON:API one.
- Return 409 Conflict when a PATCH body id does not match the URL. This also applies to a body id that
differs from the URL id only in letter case (for example an uppercase UUID): legacy repository views
used to overwrite the body id with the URL id and succeed, so clients sending such ids now get 409.


## 1.4.1 (2026-02-02)
Expand Down
5 changes: 5 additions & 0 deletions flask_jsonapi/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,11 @@ def __init__(self, detail, **kwargs):
)


class Conflict(JsonApiException):
title = 'Conflict'
status = 409


class ForbiddenError(JsonApiException):
title = 'Operation forbidden.'
status = 403
Expand Down
22 changes: 22 additions & 0 deletions flask_jsonapi/resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,18 +84,40 @@ def delete(self, *args, **kwargs):
return response.EmptyResponse()

def patch(self, *args, **kwargs):
self._check_body_id()
computed_schema = self.schema(partial=True)
try:
data = computed_schema.load(request.get_json())
except marshmallow.ValidationError as e:
return response.JsonApiErrorResponse.from_marshmallow_errors(e.messages)
else:
self._check_loaded_id(data)
resource = self.update(self.resource_id, data)
if resource:
return response.JsonApiResponse(computed_schema.dump(resource))
else:
return response.EmptyResponse()

def _check_body_id(self):
body = request.get_json(silent=True)
if not isinstance(body, dict) or not isinstance(body.get('data'), dict):
return
body_id = body['data'].get('id')
if body_id is not None and str(body_id) != str(self.resource_id):
raise self._id_conflict()

def _check_loaded_id(self, data):
# marshmallow-jsonapi lets an "id" attribute overwrite data.id in the loaded payload.
if 'id' in data and str(data['id']) != str(self.resource_id):
raise self._id_conflict()

@staticmethod
def _id_conflict():
return exceptions.Conflict(
source={'pointer': '/data/id'},
detail='Resource id in the request body does not match the URL.',
)

@property
def resource_id(self):
return self.kwargs[self.id_kwarg]
Expand Down
4 changes: 2 additions & 2 deletions flask_jsonapi/response.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,11 @@ def get_content(self):


class BaseJsonApiResponse(BaseResponse):
base_header = {'Content-Type': 'application/vnd.api+json'}
content_type = 'application/vnd.api+json'

def make_response(self):
response = super().make_response()
response.headers.extend(self.base_header)
response.headers['Content-Type'] = self.content_type
return response

def get_content(self):
Expand Down
88 changes: 88 additions & 0 deletions tests/test_resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -628,3 +628,91 @@ def test_delete_is_not_allowed(self, api, jsonapi_client):
assert len(result['errors']) == 1
error = result['errors'][0]
assert error['detail'] == 'Delete is not allowed for this resource'


class TestPatchIdCheck:
url = '/examples/f60717a3-7dc2-4f1a-bdf4-f2804c3127a4/'

def make_view(self, api, update):
class ExampleDetailView(resources.ResourceDetail):
schema = ExampleSchema

def update(self, id, data):
return update(id, data)

api.route(ExampleDetailView, 'example_detail', '/examples/<id>/')

def test_mismatched_id_is_rejected_before_update(self, api, jsonapi_client):
update = mock.Mock()
self.make_view(api, update)

response = jsonapi_client.patch(self.url, json={'data': {
'type': 'example', 'id': 'f60717a3-7dc2-4f1a-bdf4-f2804c3127a5', 'attributes': {'body': 'x'}}})

assert response.status_code == 409
assert response.get_json(force=True)['errors'] == [{
'status': 409,
'title': 'Conflict',
'detail': 'Resource id in the request body does not match the URL.',
'source': {'pointer': '/data/id'},
}]
assert not update.called

def test_missing_body_id_is_accepted(self, api, jsonapi_client):
update = mock.Mock(return_value=None)
self.make_view(api, update)

response = jsonapi_client.patch(self.url, json={'data': {'type': 'example', 'attributes': {'body': 'x'}}})

assert response.status_code == 204
assert update.called

def test_mismatched_attributes_id_without_body_id_is_rejected(self, api, jsonapi_client):
update = mock.Mock()
self.make_view(api, update)

response = jsonapi_client.patch(self.url, json={'data': {
'type': 'example', 'attributes': {'id': 'f60717a3-7dc2-4f1a-bdf4-f2804c3127a5', 'body': 'x'}}})

assert response.status_code == 409
assert not update.called

def test_mismatched_attributes_id_with_matching_body_id_is_rejected(self, api, jsonapi_client):
update = mock.Mock()
self.make_view(api, update)

response = jsonapi_client.patch(self.url, json={'data': {
'type': 'example',
'id': 'f60717a3-7dc2-4f1a-bdf4-f2804c3127a4',
'attributes': {'id': 'f60717a3-7dc2-4f1a-bdf4-f2804c3127a5', 'body': 'x'}}})

assert response.status_code == 409
assert not update.called

def test_numeric_body_id_matching_url_is_accepted(self, api, jsonapi_client):
class IntSchema(marshmallow_jsonapi.Schema):
id = fields.Int()
body = fields.Str()

class Meta:
type_ = 'example'

class ExampleDetailView(resources.ResourceDetail):
schema = IntSchema

def update(self, id, data):
return None

api.route(ExampleDetailView, 'example_detail', '/examples/<id>/')

response = jsonapi_client.patch('/examples/1/', json={'data': {
'type': 'example', 'id': 1, 'attributes': {'body': 'x'}}})

assert response.status_code == 204

def test_body_without_data_member_does_not_crash(self, api, jsonapi_client):
self.make_view(api, mock.Mock())

response = jsonapi_client.patch(self.url, json={'nodata': True})

assert response.status_code == 422
6 changes: 6 additions & 0 deletions tests/test_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,9 @@ def test_jsonapi_error_response(app):
}
]
}


def test_jsonapi_response_has_single_content_type_header(app):
with app.test_request_context('/'):
flask_response = response.JsonApiResponse({'data': None}).make_response()
assert flask_response.headers.getlist('Content-Type') == ['application/vnd.api+json']
Loading