JSON API specification for Django services
Project description
django-json-api
django-json-api uses Django's ORM interfaces as inspiration to serialize, request and deserialize entities from databases of other microservices using (and benefiting from) the JSON:API specification.
Installation
To install via pip:
pip install django-json-api
You can also install from the source:
git clone git@github.com:share-work/django-json-api.git
cd django-json-api
git checkout main
pip install -e .
Getting started
Suppose you have a django.db.models.Model
class inside microservice A, such as:
from django.db import models
class Company(models.Model):
name = models.CharField(max_length=256)
domain = models.CharField(max_length=256)
deleted_at = models.DateTimeField(null=True, default=None)
If you wish to consume it from microservice B, first add this inside the aforementioned model's definition:
class JSONAPIMeta:
resource_name = 'companies'
and define an instance of a django_json_api.models.JSONAPIModel
inside microservice B:
from django_json_api.models import JSONAPIModel
from django_json_api.fields import Attribute
class Company(JSONAPIModel):
class Meta:
api_url = MICROSERVICE_A_API_URL
resource_type = 'companies'
name = Attribute()
domain = Attribute()
PS: api_url
expects a url with protocol (i.e. starting with http(s)://
) and ending with a trailing slash /
.
Now, querying companies from microservice B is as easy as:
Company.objects.all()
Company.objects.filter(name="Sharework")
Company.objects.iterator()
...
You can also have entities in one microservice relate to entities in another by leveraging both RelatedJSONAPIField
and WithJSONAPIQuerySet
. Take a look at this model definition from microservice B:
from django.db import models
from django_json_api.django import RelatedJSONAPIField
class User(models.Model):
name = models.CharField(max_length=256)
company = RelatedJSONAPIField(json_api_model=Company)
deleted_at = models.DateTimeField(null=True, default=None)
Here, Company
is the JSONAPIModel
defined above. This makes it possible, when querying for a user, to also
fetch its related company:
user = User.objects.get(pk=1)
user.company # This will be resolved through an underlying HTTP request
In case of larger querysets, you might want to prefetch the relations as you do with django's prefetch_related
. For
that, you imbue User
's manager using WithJSONApiQuerySet
, which will grant the manager a new
method: prefetch_jsonapi
.
License
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for django_json_api-0.2.4-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 8ed7ed736bed56a5a08fbc6582b2450d72d20dd8f345347dbd5af1e3c87398bd |
|
MD5 | ff94f81c39faf88dadf9d013da5e68bd |
|
BLAKE2b-256 | 7578ade512aa5bd2b5367207e526b6ff70b70984fbe6b32f664c29e42eca0374 |