Skip to content

Latest commit

 

History

History
124 lines (83 loc) · 2.75 KB

README.md

File metadata and controls

124 lines (83 loc) · 2.75 KB

Django Spook

PyPI codecov Code style: black PyPI - Downloads

Library to interconnect multiple external HTTP APIs as Http Resources

Installation

pip install spook

Usage

Declare a serializer class for your input validation

# app/serializers.py
from rest_framework import serializers

class MySerializer(serializers.ModelSerializer):
    name = serializers.CharField()
    age = serializers.IntegerField()
    
    class Meta:
        fields = ('name', 'age', )

Declare an InputValidator

# app/validators.py
from spook.validators import InputValidator
from app.serializers import MySerializer


class MyResourceInputValidator(InputValidator):
    serializer_class = MySerializer

Declare an API Resource class.

# app/resources.py
from spook.resources import APIResource
from app.validators import MyResourceInputValidator


class MyResource(APIResource):
    api_url = 'https://my.external/api'
    validator = MyResourceInputValidator

Now you can instance MyResource class and use the methods

resource = MyResource()

# List resources
resource.list()

# Retrieve a single resource
resource.retrieve(pk=1)

# Create resource
resource.create({'name': 'Pablo', 'age': 28})

# Update resource
resource.update(pk=1, data={'name': 'Pablo Moreno'})

# Delete resource
resource.delete(pk=1)

There are also some views available

# app/views.py
from spook.views import (
    APIResourceRetrieveView, APIResourceListView, APIResourceCreateView, APIResourcePutView,
    APIResourceRetrieveUpdateView, APIResourceRetrieveUpdateDestroyView, APIResourceListCreateView,
)
from app.resources import ProductResource


class ListCreateProductResourceView(APIResourceListCreateView):
    resource = ProductResource

    def get_token(self, request):
        return ''  # We need to override get_token()


class RetrieveUpdateDestroyProductResourceView(APIResourceRetrieveUpdateDestroyView):
    resource = ProductResource

    def get_token(self, request):
        return ''

Development

We recommend to use a virtual environment

Install poetry

pip install poetry

Install dependencies

poetry install

Run tests

poetry run pytest --cov=spook