Skip to main content
Archived

This project has been archived by its maintainers, and is no longer receiving any updates.

djsonREST

djsonREST provides simple powerful features to implement your own REST-API (data encoded as json) within minutes.

The routes are versioned by default.

It also includes an addon for authentication using JWTs using consumers and users.

Base Structure of a rest route url: your_path/ + VersionMajor.Minor + /endpoint_url

Installation

Use the python package manager pip to install djsonrest.

pip install djsonrest

Dependencies

djutils

Usage

Add to your django project

Add djsonrest to your INSTALLED_APPS.

INSTALLED_APPS = [
    ...
    'djsonrest',
]

If you want to override default routes provided by djsonrest, order this app before your project app.

Add djsonrest.middleware.RESTRoutesMiddleware to your MIDDLEWARE.

MIDDLEWARE = [
    ...
    'djsonrest.middleware.RESTRoutesMiddleware',
]

If you want to customize the exception handling of rest routes override the RESTRoutesMiddleware class and configure your own middleware class instead.

Add a path for the api endpoints to your urls.py's urlpatterns.

from djsonrest import rest

urlpatterns = [
    ...
    path('api/', rest.routes.urls),
]

Define your routes

Define your own rest route using the route decorator @rest.route(...). All rest routes have to be defined in a module inside your app/project called rest_routes. This module will be automatically loaded on django initialization and so the routes are being registered.

from djsonrest import rest


class Users(rest.RESTRouteGroup):
    @rest.route('/users', version=1.0, method='GET')
    def users_get(self, request):
        return [...] # Return any json-encodable object

Using routes defined as classmethods, you can override them in inherited classes. This way you can provide extendable routes. To override the existing route, keep the route decorator the same. Change the route decorator if you want to add a second route.

class MyUsers(Users):
    @rest.route('/users', version=1.0, method='GET')
    def users_get(self, request):
        result = super().users_get(request)
        result.append([...])
        return result


class MyUsersV2(Users):
    @rest.route('/users', version=2.0, method='GET')
    def users_get(self, request):
        result = super().users_get(request)
        return {"users": result}

Routes with authentication

The route decorator provides an auth argument to which an auth class (a subclass of djsonrest.auth.Authentication) can be passed. The given auth class will be used to authenticate the request before its main processing.

There are the following authentication classes already given:

  • djsonrest.auth.Public (default) Public route, no authentication will be performed
  • djsonrest.addons.jwt_auth.auth.AbstractJWTAuth (abstract base class for JWT authentication) Expects a JWT token in the Authentication HTTP-Header with the type Bearer
  • djsonrest.addons.jwt_auth.auth.Consumer (jwt_auth addon, extends djsonrest.addons.jwt_auth.auth.AbstractJWTAuth) Expects a JWT token with the audience consumer. The request user will be the user that is defined in the consumer record
  • djsonrest.addons.jwt_auth.auth.User (jwt_auth addon, extends djsonrest.addons.jwt_auth.auth.AbstractJWTAuth) Base of UserStrong and UserWeak auth. Expects a JWT token with an audience user_strong or user_weak Tokens with the audience user_strong are only valid for 1 hour (default, can be canged in your settings), so you can use those tokens for high risk endpoints which should be only available short time after the initial authentication against the api Tokens with the audience user_weak are valid for 30 days (default, can be changed in your settings), so those tokens can be used for general interaction of a user with the api
  • djsonrest.addons.jwt_auth.auth.UserStrong (jwt_auth addon, extends djsonrest.addons.jwt_auth.auth.AbstractJWTAuth) Like User auth, but only accepts tokens with the audience user_strong
  • djsonrest.addons.jwt_auth.auth.UserWeak (jwt_auth addon, extends djsonrest.addons.jwt_auth.auth.AbstractJWTAuth) Like User auth, but only accepts tokens with the audience user_weak
from djsonrest import rest
from djsonrest.addons.jwt_auth import auth


class Users(rest.RESTRouteGroup):
    @rest.route('/users', version=1.0, method='GET', auth=auth.UserWeak)
    def users_get(self, request):
        return [...]

    @rest.route('/users/<int:id>', version=1.0, method='PATCH', auth=auth.UserStrong)
    def user_edit(self, request, id):
        # high risk action, protected by a short life token
        ...

Multiple authentication methods

If multiple authentication methods should be available, they can be combined to a HybridAuth using the |-Operator. Using a HybridAuth with the |-Operator, all of the combined authentication methods are tried after each other. This way, multiple available methods can be defined for a single route.

from djsonrest import rest, auth
from djsonrest.addons.jwt_auth import auth as jwt_auth


class Users(rest.RESTRouteGroup):
    @rest.route('/users', version=1.0, method='GET', auth=jwt_auth.UserWeak | auth.Public)
    def users_get(self, request):
        return [...]

Configure JWT Signing

To use the jwt_auth addon, some settings have to be set and files created.

Create private and public key files:

openssl ecparam -genkey -name secp521r1 -noout -out private.pem
openssl ec -in private.pem -pubout -out public.pem

Set the path to those files in your settings.py:

JWT_PRIVATE_KEY_FILE = os.path.join(BASE_DIR, 'keys', 'private.pem')
JWT_PUBLIC_KEY_FILE = os.path.join(BASE_DIR, 'keys', 'public.pem')

Remove an existing route

This is intended to be used for unwanted routes a other app registers

It is recommended that this is implemented in the __init__.py of the rest_routes module (or at the beginning if its just a file). It is possible to remove all routes with a given path (always required) or filter it by adding the version and method of the route to remove.

from djsonrest import rest

rest.remove('/unwanted/anything')
rest.remove('/unwanted/route_at_version', version=1.0)
rest.remove('/unwanted/method_route_at_version', version=1.0, method='GET')

License

GNU GPLv3, see LICENSE

Maintainer

This package is maintained by Manuel Stingl. For more information see https://opensource.voltane.eu

Metadata

Release files for djsonREST 0.2.15

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for djsonREST 0.2.15
File Size Uploaded Provenance Actions
djsonREST-0.2.15.tar.gz 31.5 kB Without provenance Details for djsonREST-0.2.15.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for djsonREST 0.2.15
File Interpreter ABI Platform Actions
djsonREST-0.2.15-py3-none-any.whl Python 3 none any Details for djsonREST-0.2.15-py3-none-any.whl

Total release size: 74.7 kB

Release files / djsonREST-0.2.15.tar.gz

Download URL djsonREST-0.2.15.tar.gz
Size 31.5 kB
Tags Source
SHA-256 checksum
How to use checksums
11003560bfe879830d6ec5ff40ba81bd1d29cbe2381ad3141a7112a005a81828
BLAKE2b-256 checksum
How to use checksums
589a457acd20d286b9f52fbefb698724ed499d0b544e82dd68e0fd3ca4e58585
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/40.8.0 requests-toolbelt/0.9.1 tqdm/4.40.1 CPython/3.7.3

Release files / djsonREST-0.2.15-py3-none-any.whl

Download URL djsonREST-0.2.15-py3-none-any.whl
Size 43.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
71692c52b9f1bf7f98812692f9fcd1fbc47b56edfd9084c95020797d89858f72
BLAKE2b-256 checksum
How to use checksums
140d1ffe508c758c0c27ab228b310d6cab34839c294096562464d5fc737086c5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/40.8.0 requests-toolbelt/0.9.1 tqdm/4.40.1 CPython/3.7.3

Security for djsonREST 0.2.15

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.

Release history Release notifications | RSS feed

This release
Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page