djrest2
A small and simple REST library for Django based on class-based views.
djrest2 provides a lightweight alternative to Django REST Framework for simple REST API needs. It's built on Django's existing class-based views and provides automatic JSON serialization, request parsing, and proper HTTP status codes out of the box.
Installation
From PyPI
pip install djrest2
From Git Repository
pip install git+https://gitlab.levitnet.be/levit/djrest.git
Development Setup
This project uses uv for dependency management:
# Clone the repository
git clone https://gitlab.levitnet.be/levit/djrest.git
cd djrest
# Create virtual environment and install dependencies
uv sync --dev
# Run the sample application
cd sample
python manage.py migrate
python manage.py runserver
Quick Start Guide
1. Create API Views
from django.db import models
from djrest import ListCreateView, UpdateDeleteView
class Category(models.Model):
name = models.CharField(max_length=255)
class CategoryListCreateView(ListCreateView):
model = Category
fields = ('name',)
class CategoryUpdateDeleteView(UpdateDeleteView):
model = Category
fields = ('name',)
2. Configure URLs
from django.urls import path
from . import views
urlpatterns = [
path('api/categories/', views.CategoryListCreateView.as_view()),
path('api/categories/<int:pk>/', views.CategoryUpdateDeleteView.as_view()),
]
3. Use the API
# List categories
curl http://localhost:8000/api/categories/
# Create a category
curl -X POST http://localhost:8000/api/categories/ \
-H "Content-Type: application/json" \
-d '{"name": "Electronics"}'
# Update a category
curl -X PUT http://localhost:8000/api/categories/1/ \
-H "Content-Type: application/json" \
-d '{"name": "Updated Electronics"}'
# Delete a category
curl -X DELETE http://localhost:8000/api/categories/1/
API Reference
For comprehensive API documentation, generate the docs using django-classy-doc:
python sample/manage.py classify -o docs/api/$(python -c "from djrest.__version__ import __version__; print(__version__)")/
Core Classes
JsonResponse: Extended Django JsonResponse that handles empty data for 204 status codesRestViewMixin: Base mixin providing JSON serialization, request parsing, and form handlingListCreateView: Combines Django's BaseListView and BaseCreateView for collection endpointsUpdateDeleteView: Extends BaseUpdateView with PUT/DELETE support for individual resources
Advanced Usage
Pagination
djrest2 supports pagination through Django's built-in pagination. When you add paginate_by to your view, the response will include pagination metadata:
class CategoryListCreateView(ListCreateView):
model = Category
fields = ('name',)
paginate_by = 10 # Enable pagination with 10 items per page
Response format with pagination:
{
"results": [
{"pk": 1, "name": "Electronics"},
{"pk": 2, "name": "Books"}
],
"pagination": {
"count": 25,
"page": 1,
"num_pages": 3
}
}
Without pagination, only the results array is returned:
{
"results": [
{"pk": 1, "name": "Electronics"},
{"pk": 2, "name": "Books"}
]
}
You can customize the pagination metadata by overriding get_pagination_metadata():
class CustomPaginatedView(ListCreateView):
model = Product
fields = ('name', 'price')
paginate_by = 20
def get_pagination_metadata(self, context):
metadata = super().get_pagination_metadata(context)
if metadata:
# Add custom fields to pagination metadata
metadata['page_size'] = self.paginate_by
return metadata
Custom Serialization
class ProductListCreateView(ListCreateView):
model = Product
fields = ('name', 'price', 'category')
def serialize_one(self, obj):
data = super().serialize_one(obj)
data['category_name'] = obj.category.name
return data
Error Handling
class CustomAPIView(ListCreateView):
model = MyModel
fields = ('field1', 'field2')
def handle_json_error(self, error):
# Custom JSON error handling
return self.response_class(
{'custom_error': str(error)},
status=400
)
Authentication Integration
from django.contrib.auth.mixins import LoginRequiredMixin
class ProtectedCategoryView(LoginRequiredMixin, ListCreateView):
model = Category
fields = ('name',)
Configuration
Add these optional settings to your Django settings:
# Maximum JSON request body size (default: 10MB)
DJREST_MAX_JSON_SIZE = 10 * 1024 * 1024
Testing
Run tests using nox to test across multiple Python and Django versions:
# Run all tests
nox
# Run tests for specific Python/Django combination
nox -s "test-3.12(django='5.1')"
# Run linting
nox -s lint
# Generate documentation
nox -s docs
Or run tests directly:
cd sample
python manage.py test shop.tests
Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature-name) - Make your changes
- Run tests (
nox) - Commit your changes (
git commit -am 'Add feature') - Push to the branch (
git push origin feature-name) - Create a Pull Request
Development Tools
This project uses:
- ruff for linting and formatting
- nox for testing across environments
- pre-commit for git hooks
- pytest for testing
- factory-boy for test data generation
Design Philosophy
dj-rest is designed to be minimal yet powerful. Read more about the motivation and design principles in Emma's blog post: Why do we need an external app for REST?
License
MIT License - see LICENSE file for details.
Metadata
Release files for djrest2 0.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| djrest2-0.2.0.tar.gz | 7.6 kB | Without provenance | Details for djrest2-0.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| djrest2-0.2.0-py3-none-any.whl | Python 3 | none | any | Details for djrest2-0.2.0-py3-none-any.whl |
Total release size: 14.9 kB
Release files / djrest2-0.2.0.tar.gz
| Download URL | djrest2-0.2.0.tar.gz |
|---|---|
| Size | 7.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
e15c93e2b78b86e86130af2535c27c1176c3028880b4d861e2268791e5e7e999
|
|
BLAKE2b-256 checksum How to use checksums |
276cb9945c4e5c985edfe6e2db53fd9d78ab3e3a183aafcb16201c38b5b0f8ad
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.13.0
|
Release files / djrest2-0.2.0-py3-none-any.whl
| Download URL | djrest2-0.2.0-py3-none-any.whl |
|---|---|
| Size | 7.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
7bfcdfc85bcc1077ae5d713a173713a12b45e814e08b3ca75c7abe32a4324f2c
|
|
BLAKE2b-256 checksum How to use checksums |
9dde134d0b6e9e2cb770d09b2b6e2a2befd58c976a4a25cefe47c52ddf60e30f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.13.0
|
Security for djrest2 0.2.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.