18.5. Ninja DELETE

18.5.1. HTTP Schemas

File myproject/schemas.py:

>>> 
... from ninja import Schema
...
...
... class OkResponse(Schema):
...     status: int = 200
...     reason: str = 'Ok'
...     data: str
...
...
... class CreatedResponse(Schema):
...     status: int = 201
...     reason: str = 'Created'
...     data: str
...
...
... class BadRequestResponse(Schema):
...     status: int = 400
...     reason: str = 'Bad request'
...     data: str
...
...
... class NotFoundResponse(Schema):
...     status: int = 404
...     reason: str = 'Not found'
...     data: str
...
...
... class UnauthorizedResponse(Schema):
...     status: int = 401
...     reason: str = 'Unauthorized'
...     data: str

18.5.2. API Endpoint

File shop/api.py:

>>> 
... from django.http import HttpRequest
... from ninja import Router
... from auth.api import SessionID
... from myproject.schemas import CreatedResponse, BadRequestResponse
... from shop.models import Product
... from shop.schemas import ProductSchema
...
...
... router = Router()
...
...
... @router.delete('/product', auth=SessionID(), response={
...     200: OkResponse,
...     400: BadRequestResponse,
...     404: NotFoundResponse})
... def product_delete(request: HttpRequest, product_id: int):
...     try:
...         Product.objects.delete(**product.dict())
...         return 200, {'data': 'Product deleted'}
...     except Product.DoesNotExist:
...         return 404, {'data': 'Product not found'}
...     except Exception as error:
...         return 400, {'data': str(error)}