Skip to main content

Lightweight API infrastructure toolkit for standardized responses, errors, and retry handling.

Project description

Apicore

Lightweight API infrastructure toolkit for Django REST Framework providing standardized responses, errors, permissions, CRUD operations, and default data initialization.

Features

  • BaseModel - Abstract model with timestamps, soft delete, and common fields
  • BaseViewSet - Pre-configured CRUD operations with standardized responses
  • Standardized API Responses - Consistent success/error response format
  • Custom Exception Classes - ApiError, ValidationError, NotFoundError, UnauthorizedError, ForbiddenError
  • Permission Classes - IsOwner, IsActiveUser, ReadOnly
  • Pagination - StandardPagination with metadata
  • Request Tracing - Decorator for logging with UUID and timing
  • Default Data Initializer - Load default data for multiple models from JSON
  • Common Constants - HTTP status codes, error codes, pagination defaults

Installation

pip install hiten-apicore

Quick Start

1. BaseModel

from django.db import models
from apicore import BaseModel

class Product(BaseModel):
    name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    description = models.TextField(blank=True)

# Includes: created_at, updated_at, is_active fields
# Methods: soft_delete(), restore()

2. BaseViewSet

from rest_framework import serializers
from apicore import BaseViewSet, StandardPagination, IsActiveUser

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = '__all__'

class ProductViewSet(BaseViewSet):
    queryset = Product.objects.filter(is_active=True)
    serializer_class = ProductSerializer
    permission_classes = [IsActiveUser]
    pagination_class = StandardPagination

3. Permissions

from apicore import IsOwner, IsActiveUser, ReadOnly

class MyViewSet(BaseViewSet):
    permission_classes = [IsActiveUser, IsOwner]

4. Error Handling

from apicore import NotFoundError, ValidationError, UnauthorizedError

def my_view(request):
    if not obj:
        raise NotFoundError("Product not found")
    if not valid:
        raise ValidationError("Invalid data", errors={"field": "error"})
    if not authorized:
        raise UnauthorizedError("Access denied")

5. Request Tracing

from apicore import trace_request

class MyViewSet(BaseViewSet):
    @trace_request
    def list(self, request, *args, **kwargs):
        return super().list(request, *args, **kwargs)

6. Initialize Default Data

Create JSON file (defaults.json):

{
  "myapp.Category": {
    "lookup_fields": ["code"],
    "data": [
      {"code": "electronics", "name": "Electronics"},
      {"code": "clothing", "name": "Clothing"}
    ]
  },
  "myapp.Status": {
    "lookup_fields": ["code"],
    "data": [
      {"code": "active", "name": "Active"},
      {"code": "inactive", "name": "Inactive"}
    ]
  }
}

Load data:

python manage.py initialize_defaults defaults.json

Or in Python:

from apicore import initialize_from_json

results = initialize_from_json('defaults.json')
# Returns: {'myapp.Category': {'created': 2, 'updated': 0, 'total': 2}}

Response Format

Success:

{
    "status": "success",
    "data": {...},
    "message": "Operation successful",
    "meta": {
        "pagination": {
            "count": 100,
            "page_size": 10,
            "current_page": 1,
            "total_pages": 10
        }
    }
}

Error:

{
    "status": "error",
    "message": "Error message",
    "error_code": "VALIDATION_ERROR",
    "errors": {"field": "error detail"}
}

Available Components

Models

  • BaseModel - Abstract model with common fields

ViewSets

  • BaseViewSet - CRUD operations with standardized responses

Responses

  • ApiResponse.success(data, message, meta)
  • ApiResponse.error(message, error_code, errors)

Errors

  • ApiError(message, status_code, error_code)
  • ValidationError(message, errors)
  • NotFoundError(message)
  • UnauthorizedError(message)
  • ForbiddenError(message)

Permissions

  • IsOwner - Check if user owns the object
  • IsActiveUser - Check if user is active
  • ReadOnly - Allow only GET, HEAD, OPTIONS

Pagination

  • StandardPagination - Page-based pagination with metadata

Utilities

  • trace_request - Decorator for request logging
  • initialize_from_json(path) - Load defaults from JSON
  • initialize_from_dict(data) - Load defaults from dict
  • DefaultDataInitializer - Class-based initializer

Constants

  • HTTP_STATUS_CODES - Common HTTP status codes
  • ERROR_CODES - Standard error codes
  • DEFAULT_PAGE_SIZE - Default pagination size (10)
  • MAX_PAGE_SIZE - Maximum pagination size (100)

Requirements

  • Python >= 3.8
  • Django >= 4.0
  • djangorestframework >= 3.14.0

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

hiten_apicore-0.1.2.tar.gz (13.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

hiten_apicore-0.1.2-py3-none-any.whl (13.5 kB view details)

Uploaded Python 3

File details

Details for the file hiten_apicore-0.1.2.tar.gz.

File metadata

  • Download URL: hiten_apicore-0.1.2.tar.gz
  • Upload date:
  • Size: 13.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.9

File hashes

Hashes for hiten_apicore-0.1.2.tar.gz
Algorithm Hash digest
SHA256 41922a2ce97e069f014c85478cec7b29515595dfd02cc7dc2492ca533f6287df
MD5 a4fab28f3ceca84f3e2c3b660db387b0
BLAKE2b-256 56a254168b1f05ba591ba0ef37adc15d829cd6f94fbdef4d412d547877c68944

See more details on using hashes here.

File details

Details for the file hiten_apicore-0.1.2-py3-none-any.whl.

File metadata

  • Download URL: hiten_apicore-0.1.2-py3-none-any.whl
  • Upload date:
  • Size: 13.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.9

File hashes

Hashes for hiten_apicore-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 784dfd3efeeb9a48d56fe5d77b46c58ca1f3075e5cfbdc24af08ee4359f75550
MD5 892594001dab9e0b91979a10284e1ee5
BLAKE2b-256 752727ef374847ba8251414fd39e4cac49397a48270e88dcd6aa70fef0132ac8

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page