Package: djsonREST
djsonRESTdjsonREST 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_urlInstallationUse the python package manager pip to install djsonrest.pipinstalldjsonrestDependenciesdjutilsUsageAdd to your django projectAdddjsonrestto yourINSTALLED_APPS.INSTALLED_APPS=[...'djsonrest',]If you want to override default routes provided by djsonrest, order this app before your project app.Adddjsonrest.middleware.RESTRoutesMiddlewareto yourMIDDLEWARE.MIDDLEWARE=[...'djsonrest.middleware.RESTRoutesMiddleware',]If you want to customize the exception handling of rest routes override theRESTRoutesMiddlewareclass and
configure your own middleware class instead.Add a path for the api endpoints to your urls.py'surlpatterns.fromdjsonrestimportresturlpatterns=[...path('api/',rest.routes.urls),]Define your routesDefine your own rest route using the route decorator@rest.route(...).
All rest routes have to be defined in a module inside your app/project calledrest_routes.
This module will be automatically loaded on django initialization and so the routes are being registered.fromdjsonrestimportrestclassUsers(rest.RESTRouteGroup):@rest.route('/users',version=1.0,method='GET')defusers_get(self,request):return[...]# Return any json-encodable objectUsing 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.classMyUsers(Users):@rest.route('/users',version=1.0,method='GET')defusers_get(self,request):result=super().users_get(request)result.append([...])returnresultclassMyUsersV2(Users):@rest.route('/users',version=2.0,method='GET')defusers_get(self,request):result=super().users_get(request)return{"users":result}Routes with authenticationThe route decorator provides anauthargument to which an auth class (a subclass ofdjsonrest.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 performeddjsonrest.addons.jwt_auth.auth.AbstractJWTAuth(abstract base class for JWT authentication)
Expects a JWT token in theAuthenticationHTTP-Header with the typeBearerdjsonrest.addons.jwt_auth.auth.Consumer(jwt_auth addon, extendsdjsonrest.addons.jwt_auth.auth.AbstractJWTAuth)
Expects a JWT token with the audienceconsumer. The request user will be the user that is defined in the consumer recorddjsonrest.addons.jwt_auth.auth.User(jwt_auth addon, extendsdjsonrest.addons.jwt_auth.auth.AbstractJWTAuth)
Base ofUserStrongandUserWeakauth. Expects a JWT token with an audienceuser_strongoruser_weakTokens with the audienceuser_strongare 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 audienceuser_weakare 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 apidjsonrest.addons.jwt_auth.auth.UserStrong(jwt_auth addon, extendsdjsonrest.addons.jwt_auth.auth.AbstractJWTAuth)
LikeUserauth, but only accepts tokens with the audienceuser_strongdjsonrest.addons.jwt_auth.auth.UserWeak(jwt_auth addon, extendsdjsonrest.addons.jwt_auth.auth.AbstractJWTAuth)
LikeUserauth, but only accepts tokens with the audienceuser_weakfromdjsonrestimportrestfromdjsonrest.addons.jwt_authimportauthclassUsers(rest.RESTRouteGroup):@rest.route('/users',version=1.0,method='GET',auth=auth.UserWeak)defusers_get(self,request):return[...]@rest.route('/users/<int:id>',version=1.0,method='PATCH',auth=auth.UserStrong)defuser_edit(self,request,id):# high risk action, protected by a short life token...Multiple authentication methodsIf multiple authentication methods should be available, they can be combined to aHybridAuthusing the|-Operator.
Using aHybridAuthwith 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.fromdjsonrestimportrest,authfromdjsonrest.addons.jwt_authimportauthasjwt_authclassUsers(rest.RESTRouteGroup):@rest.route('/users',version=1.0,method='GET',auth=jwt_auth.UserWeak|auth.Public)defusers_get(self,request):return[...]Configure JWT SigningTo use the jwt_auth addon, some settings have to be set and files created.Create private and public key files:opensslecparam-genkey-namesecp521r1-noout-outprivate.pem
opensslec-inprivate.pem-pubout-outpublic.pemSet the path to those files in yoursettings.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 routeThis is intended to be used for unwanted routes a other app registersIt is recommended that this is implemented in the__init__.pyof therest_routesmodule (or at the beginning if its just a file).
It is possible to remove all routes with a givenpath(always required) or filter it by adding the version and method of the route to remove.fromdjsonrestimportrestrest.remove('/unwanted/anything')rest.remove('/unwanted/route_at_version',version=1.0)rest.remove('/unwanted/method_route_at_version',version=1.0,method='GET')LicenseGNU GPLv3, see LICENSEMaintainerThis package is maintained by Manuel Stingl.
For more information seehttps://opensource.voltane.eu