question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Problem getting JSON response to contain JSON API data attribute, etc.

See original GitHub issue

I am using Django REST Framework JSON API:

https://github.com/django-json-api/django-rest-framework-json-api

I have the following model:

class Question(BaseModel):
    text = models.TextField(unique=True)
    members = models.ManyToManyField(Member, related_name='questions')

    def __str__(self):
        return self.text

    class JSONAPIMeta:
        resource_name = "questions"


class Answer(BaseModel):
    text = models.TextField(blank=True)
    icon = models.TextField()
    question = models.ForeignKey(Question, related_name='answers')

    def __str__(self):
        return self.text or self.icon

    class JSONAPIMeta:
        resource_name = "answers"

and the following serializers:

class AnswerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Answer
        fields = ('text', 'icon')


class QuestionSerializer(serializers.ModelSerializer):
    answers = AnswerSerializer(many=True, read_only=True)

    class Meta:
        model = Question
        fields = ('text', 'answers')

and the following views:

class QuestionViewSet(viewsets.ReadOnlyModelViewSet):
    """
    API endpoint that allows questions and answers to be read.
    """
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer
    renderers = renderers.JSONRenderer
    parsers = parsers.JSONParser

However, when I test the API asking for pk=1, the JSON response does not conform to the JSON API specs:

{"text": "Are you dizzy?", "answers": [{"text": "No", "icon": "icon-no"}, {"text": "A little dizzy", "icon": "icon-dizzy-somewhat"}, {"text": "Very dizzy", "icon": "icon-dizzy-very"}]}

I’m importing the various renderers and parsers from the DRF JSON API package, and the endpoints are being generated by the viewset. How can I make the responses contain the proper data attribute and conform to the JSON API spec?

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Comments:7

github_iconTop GitHub Comments

1reaction
leifurhaukscommented, Feb 17, 2016

An unfortunate peculiarity of the django test client is that headers need to be in the WSGI format, thus HTTP_ACCEPT instead of Accept. I had the same problem once; I ended spending about two or three hours debugging with the test client before I figured that out.

1reaction
davidthewatsoncommented, Feb 17, 2016

Thanks, again.

Turns out that setting the accept header to application/vnd.api+json generates a 406. That surprised me and seems to suggest that the JSON API renderers are not hooked up.

And I was puzzling over the plurality of the attributes in renderers and parsers with the singularity of the rvalues. I changed to the tuple spec as you suggested, but the results are still the same.

I even restarted the django debug server because it seemed weird. Then I ran with renderers and parsers removed and the client side result was the same.

Then I decided to look at the base classes. BINGO! It’s not renderers and parsers. It’s:

renderer_classes = (renderers.JSONRenderer,)
parser_classes = (parsers.JSONParser,)

And then the response looked like this, of course:

{
  "data": {
    "type": "questions",
    "id": "1",
    "attributes": {
      "text": "Are you dizzy?"
    },
    "relationships": {
      "answers": {
        "data": [
          {
            "type": "answers",
            "id": "1"
          },
          {
            "type": "answers",
            "id": "2"
          },
          {
            "type": "answers",
            "id": "3"
          }
        ]
      }
    }
  }

Now I can’t even find the code example that I copied this pattern from. It may not exist! Sorry for the trouble @leifurhauks, but thanks for the debugging help. I’d be happy to make a pull request on the docs with the specific viewset example so that this never happens again.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Presence of data in request and response - JSON API
Hello, the specification seems to be quite clear that a data JSON attribute named data should be present in JSON response and request...
Read more >
API Call get the response in JSON and extract the data
Solved: @ Matt Burgess I need one help I have one rest API and that API return the response in JSON format. In...
Read more >
How can I associate JSON object of the api response to java ...
You can create a wrapper class that match the json response : an object with only one attribute named "data" type of desire...
Read more >
Fetching resources (GET) | JSON:API module - Drupal
The response body contains the JSON:API object of a single article node, including attributes, relationships, and links. GET multiple articles.
Read more >
Common API mistakes and how to avoid them - LogRocket Blog
json ({ error: false, // expected JSON response data: 'Hello World!' }); }); app.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found