Skip to content

1. The envelope

The settings

Three lines in REST_FRAMEWORK, each independent of the others:

example/config/settings.py
REST_FRAMEWORK = {
    # Nobody signs in to the example: it shows the shape of the answers, not who may ask.
    'DEFAULT_AUTHENTICATION_CLASSES': [],
    'DEFAULT_PERMISSION_CLASSES': [],
    'UNAUTHENTICATED_USER': None,
    # drf-parcel: the three lines - each works without the others.
    'EXCEPTION_HANDLER': 'drf_parcel.handlers.exception_handler',
    'DEFAULT_PAGINATION_CLASS': 'drf_parcel.pagination.PageNumberPagination',
    'DEFAULT_SCHEMA_CLASS': 'drf_parcel.schema.ParcelAutoSchema',
}

A viewset in the envelope

example/shop/api.py
class ProductViewSet(EnvelopeMixin, viewsets.ModelViewSet[Product]):
    """Products, a numbered page at a time."""

    queryset = Product.objects.all()
    serializer_class = ProductSerializer

    # drf-parcel: the client may send ?page_size=, and never gets more than 20.
    client_page_size = True
    max_page_size = 20

    # drf-parcel: this view's own sentence for one action; the rest say the default.
    envelope_messages = {'create': _('The product was added.')}

    def perform_destroy(self, instance: Product) -> None:
        services.delete_product(instance)

    @action(detail=True, methods=['post'])
    def restock(self, request: Request, pk: str) -> Response:
        """Add to the stock - an answer written by hand, with a message of its own."""
        product = self.get_object()
        asked = RestockSerializer(data=request.data)
        asked.is_valid(raise_exception=True)
        product.stock += asked.validated_data['quantity']
        product.save(update_fields=['stock'])
        return success_response(
            ProductSerializer(product).data, message=_('The stock was updated.')
        )

Three things to notice:

  1. EnvelopeMixin comes first. It wraps what the view answers in finalize_response, once - list, create, destroy and the restock action alike.
  2. envelope_messages gives one action a sentence of its own. Every other action says the default, read off the request.
  3. restock answers by hand with success_response. An answer already in the envelope is never wrapped twice.

What each answer says

When nobody wrote a message, it is read off the request:

the request the message
answered 201 Created.
PUT or PATCH Saved.
DELETE Deleted.
anything else Done.
curl -X POST -H 'Content-Type: application/json' \
     -d '{"name": "Brooch", "price": "60.00"}' http://127.0.0.1:8000/api/products/
{"success": true, "status_code": 201, "message": "The product was added.",
 "data": {"id": 29, "name": "Brooch", "price": "60.00", "stock": 0}}

The view's own sentence, because create named one. A message is replaced at three levels, the nearest winning: one answer (success_response(..., message=...)), one view (envelope_messages), or the whole project (DRF_PARCEL['MESSAGES']).

A delete is a 200

DELETE /api/products/29/ answers 200 with the envelope and "Deleted.", not 204. A 204 carries no body by definition, so the client would have nothing to read.

Next

2. Pages