17.2. Ninja GET

File myproject/schemas.py:

17.2.1. HTTP Schemas

>>> 
... 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.2.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.2.3. API Endpoints

File myproject/shop/api.py:

>>> 
... from django.http import HttpRequest
... from ninja import Router
... from ninja.pagination import paginate, PageNumberPagination
... from auth.api import SessionID
... from myproject.schemas import BadRequestResponse, NotFoundResponse, OkResponse
... from shop.models import Product
... from shop.schemas import ProductSchema
...
...
... router = Router()
...
...
... @router.get('/products', response=list[ProductSchema])
... @paginate(PageNumberPagination, page_size=5)
... def products_list(request: HttpRequest):
...     products = Product.objects.all().values('name', 'price', 'barcode')
...     return list(products)
...
...
... @router.get('/product', response=ProductSchema)
... def products_list(request: HttpRequest, name: str = None, barcode: str = None) -> dict:
...     if name is not None:
...         product = Product.objects.get(name=name)
...     elif barcode is not None:
...         product = Product.objects.get(barcode=barcode)
...     else:
...         return {'status': 400, 'reason': 'Bad request'}
...     data = vars(product)
...     data.pop('_state')
...     return data
...
...
... @router.get('/product/{pk}', response={
...     200: ProductSchema,
...     404: NotFoundResponse})
... def product_details(request: HttpRequest, pk: int):
...     try:
...         product = Product.objects.get(pk=pk)
...     except Product.DoesNotExist:
...         return 404, {'data': 'Product not found'}
...     else:
...         data = vars(product)
...         data.pop('_state')
...         return 200, data

17.2.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 API Details
# - Difficulty: easy
# - Lines: 8
# - Minutes: 8

# %% English
# 0. Use `myproject.shop`
# 1. Create an endpoint `GET /api/v2/shop/product/{pk}`
# 2. Endpoint will return product details for given `pk`
# 3. Primary Key of the product will be passed in `pk` parameter
# 4. Use package `ninja`

# %% Polish
# 0. Użyj `myproject.shop`
# 1. Stwórz endpoint `GET /api/v2/shop/product/{pk}`
# 2. Endpoint na zwróci szczegóły produktu dla danego `pk`
# 3. Primary Key produktu zostanie przekazany w parametrze `pk`
# 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()

...

# 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 API Details
# - Difficulty: easy
# - Lines: 8
# - Minutes: 8

# %% English
# 0. Use `myproject.shop`
# 1. Create an endpoint `GET /api/v2/shop/product`
# 2. Endpoint will return product details for given `name` or `barcode`
# 3. `name` or `barcode` will be passed in query parameters
# 4. Use package `ninja`

# %% Polish
# 0. Użyj `myproject.shop`
# 1. Stwórz endpoint `GET /api/v2/shop/product`
# 2. Endpoint na zwróci szczegóły produktu dla danego `name` lub `barcode`
# 3. `name` lub `barcode` zostaną przekazane w parametrach zapytania
# 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()

...