Skip to content

Commit 252bdbc

Browse files
committed
Parser is now JSON:API compliant
1 parent 377a018 commit 252bdbc

File tree

1 file changed

+38
-7
lines changed

1 file changed

+38
-7
lines changed

rest_framework_json_api/parsers.py

Lines changed: 38 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33
"""
44
from rest_framework import parsers
55

6-
from . import utils, renderers
6+
from . import utils, renderers, exceptions
7+
78

89
class JSONParser(parsers.JSONParser):
910
"""
@@ -29,10 +30,40 @@ def parse(self, stream, media_type=None, parser_context=None):
2930
"""
3031
Parses the incoming bytestream as JSON and returns the resulting data
3132
"""
32-
result = super(JSONParser, self).parse(stream, media_type=media_type,
33-
parser_context=parser_context)
33+
result = super(JSONParser, self).parse(stream, media_type=media_type, parser_context=parser_context)
3434
data = result.get('data', {})
35-
attributes = data.get('attributes')
36-
if attributes:
37-
attributes['id'] = data.get('id')
38-
return utils.format_keys(attributes, 'underscore')
35+
36+
if data:
37+
# Check for inconsistencies
38+
resource_name = utils.get_resource_name(parser_context)
39+
if data.get('type') != resource_name:
40+
raise exceptions.Conflict(
41+
"The resource object's type ({data_type}) is not the type "
42+
"that constitute the collection represented by the endpoint ({resource_type}).".format(
43+
data_type=data.get('type'),
44+
resource_type=resource_name
45+
)
46+
)
47+
# Get the ID
48+
data_id = data.get('id')
49+
# Get the attributes
50+
attributes = utils.format_keys(data.get('attributes'), 'underscore') if data.get(
51+
'attributes') else dict()
52+
# Get the relationships
53+
relationships = utils.format_keys(data.get('relationships'), 'underscore') if data.get(
54+
'relationships') else dict()
55+
56+
# Parse the relationships
57+
parsed_relationships = dict()
58+
for field_name, field_data in relationships.items():
59+
field_data = field_data.get('data')
60+
if isinstance(field_data, dict):
61+
parsed_relationships[field_name] = field_data.get('id')
62+
elif isinstance(field_data, list):
63+
parsed_relationships[field_name] = list(relation.get('id') for relation in field_data)
64+
65+
# Construct the return data
66+
parsed_data = {'id': data_id}
67+
parsed_data.update(attributes)
68+
parsed_data.update(parsed_relationships)
69+
return parsed_data

0 commit comments

Comments
 (0)