NSJ Rest Lib

6.4.1 · active · verified Fri Apr 17

nsj-rest-lib is a Python library for building declarative REST APIs, adhering to internal guidelines and focusing on DTO (Data Transfer Object) and Entity patterns. It simplifies API creation by abstracting common patterns for data mapping, validation, and persistence. The current version is 6.4.1, and it maintains an active release cadence with regular feature additions and bug fixes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define an Entity (mapping to a database table) and various DTOs (Data Transfer Objects) for API representation, including using `DTOAggregator` for nested structures that map to a single underlying entity. This setup forms the core declarative definition for building REST APIs with nsj-rest-lib.

from dataclasses import dataclass
from nsj_rest_lib.dto.dto_base import DTOBase
from nsj_rest_lib.dto.fields import DTOField, DTOAggregator
from nsj_rest_lib.entity.entity_base import EntityBase

# 1. Define your Entity (maps to a database table)
@dataclass
class ProductEntity(EntityBase):
    id: int
    name: str
    description: str
    price: float

# 2. Define your DTO (Data Transfer Object, maps to API representation)
class ProductDTO(DTOBase):
    id: int = DTOField(pk=True)
    name: str = DTOField()
    price: float = DTOField(decimal_places=2)

# 3. Example of an aggregated DTO using DTOAggregator (v4.9.0+)
class ProductDetailsDTO(DTOBase):
    category: str = DTOField()
    weight_kg: float = DTOField()

class FullProductDTO(DTOBase):
    id: int = DTOField(pk=True)
    name: str = DTOField()
    description: str = DTOField()
    details: ProductDetailsDTO = DTOAggregator()

print("DTOs and Entities defined successfully.")
print(f"ProductDTO fields: {ProductDTO.get_fields()}")
print(f"FullProductDTO fields: {FullProductDTO.get_fields()}")

view raw JSON →