Complete worked example
python
from drf_lab import setup
setup()
import json
from rest_framework.decorators import api_view, parser_classes
from rest_framework.parsers import JSONParser, FormParser
from rest_framework.response import Response
from rest_framework.test import APIRequestFactory
@api_view(["POST"])
@parser_classes([JSONParser])
def create(request):
return Response({"title": request.data.get("title", "")}, status=201)
def inspect_example(payload):
raw = payload.get("raw", json.dumps(payload.get("body", {})))
request = APIRequestFactory().post("/roles/", data=raw,
content_type=payload.get("type", "application/json"))
response = create(request)
body = {"error": response.data["detail"].code} if response.status_code >= 400 else response.data
response.render()
return {"status": response.status_code, "body": body}- Reasoning
- The Content-Type header selects how the body is parsed. A valid JSON mapping reaches the view, malformed JSON becomes a parse failure, and an unsupported media type is rejected when request.data is accessed. The helper renders the response and compares the decoded public JSON. Rendering matters: response.data is a Python representation, whereas a client receives encoded bytes and a status. The test reports both. The endpoint deliberately echoes a tiny fixture title; later serializer lessons add the validation boundary that this introductory route does not yet claim.