18.3. Ninja POST

18.3.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.3.2. Custom Schemas

File shop/schemas.py:

>>> 
... from ninja import Schema
...
...
... class ProductSchema(Schema):
...     ean13: str
...     name: str
...     price: float
...
...     model_config = {
...         'json_schema_extra': {
...             'example': {
...                 'name': 'My Product',
...                 'ean13': '1234567890123',
...                 'price': 123.45}}}

18.3.3. 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.post('/product', auth=SessionID(), response={
...     201: CreatedResponse,
...     400: BadRequestResponse})
... def product_create(request: HttpRequest, product: ProductSchema):
...     try:
...         Product.objects.create(**product.dict())
...         return 201, {'data': 'Product created'}
...     except Exception as error:
...         return 400, {'data': str(error)}