17.3. Ninja POST

17.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

17.3.2. Custom Schemas

File myproject/shop/schemas.py:

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

17.3.3. API Endpoint

File myproject/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)}

17.3.4. Assignments

# FIXME: Write tests

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Django Ninja Create
# - Difficulty: easy
# - Lines: 8
# - Minutes: 8

# %% English
# 0. Use `myproject.shop`
# 1. Create an endpoint `POST /api/v2/shop/product/`
# 2. Endpoint will return product details for given `pk`
# 3. Input data:
#    - `name` - product name
#    - `barcode` - barcode in EAN-13 format
#    - `price` - product price
# 4. Use package `ninja`

# %% Polish
# 0. Użyj `myproject.shop`
# 1. Stwórz endpoint `POST /api/v2/shop/product/`
# 2. Endpoint ma dodawać rekordy do bazy danych
# 3. Dane wejściowe:
#    - `name` - nazwa produktu
#    - `barcode` - kod kreskowy w formacie EAN-13
#    - `price` - cena produktu
# 4. Użyj pakietu `ninja`

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 10), \
'Python 3.10+ required'
"""

# Required for Django to work
import os; os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
import django; django.setup()

...