Quickstart¶
A viewset in the envelope, a page, and a failure - in a project installed as the last page says.
1. Give the view the mixin¶
from rest_framework.viewsets import ModelViewSet
from drf_parcel.responses import EnvelopeMixin
class ProductViewSet(EnvelopeMixin, ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
EnvelopeMixin comes first, before DRF's classes. It wraps what the view
answers once, in finalize_response, so no action - list, create, an
@action of your own - has to remember.
2. Ask it¶
3. Raise your own error¶
from django.utils.translation import gettext_lazy as _
from drf_parcel.exceptions import DomainError
class OutOfStockError(DomainError):
status_code = 409
default_code = 'out_of_stock'
default_detail = _('There is not enough of this product in stock.')
raise OutOfStockError(data={'available': product.stock})
{"success": false, "status_code": 409, "message": "There is not enough of this product in stock.",
"data": {"available": 0}, "error_code": "out_of_stock"}
A DomainError is DRF's own APIException with data added, so it is
raised from a service, a task or a command alike.
Next¶
- The tutorial builds the example shop a part at a time.
- Adopt it in an existing project - a project with an envelope of its own already.
- The contract has every shape and every error code.