Django API creation with signed requests utilizing forms for validation.

Related tags

Djangodjango-formapi
Overview

django-formapi

Create JSON API:s with HMAC authentication and Django form-validation.

https://travis-ci.org/5monkeys/django-formapi.svg?branch=master https://coveralls.io/repos/github/5monkeys/django-formapi/badge.svg?branch=master

Version compatibility

See Travis-CI page for actual test results: https://travis-ci.org/5monkeys/django-formapi

Django Python 2.6 2.7 3.3 3.4 3.5 3.6
1.3 Yes Yes        
1.4 Yes Yes        
1.5 Yes Yes Yes      
1.6 Yes Yes Yes      
1.7   Yes Yes Yes    
1.8   Yes Yes Yes Yes Yes
1.9   Yes   Yes Yes Yes
1.10   Yes   Yes Yes Yes

Installation

Install django-formapi in your python environment

$ pip install django-formapi

Add formapi to your INSTALLED_APPS setting.

INSTALLED_APPS = (
    ...
    'formapi',
)

Add formapi.urls to your urls.py.

urlpatterns = patterns('',
    ...
    url(r'^api/', include('formapi.urls')),
)

Usage

Go ahead and create a calls.py.

class DivisionCall(calls.APICall):
    """
    Returns the quotient of two integers
    """
    dividend = forms.FloatField()
    divisor = forms.FloatField()

    def action(self, test):
        dividend = self.cleaned_data.get('dividend')
        divisor = self.cleaned_data.get('divisor')
        return dividend / divisor

API.register(DivisionCall, 'math', 'divide', version='v1.0.0')

Just create a class like your regular Django Forms but inheriting from APICall. Define the fields that your API-call should receive. The action method is called when your fields have been validated and what is returned will be JSON-encoded as a response to the API-caller. The API.register call takes your APICall-class as first argument, the second argument is the namespace the API-call should reside in, the third argument is the name of your call and the fourth the version. This will result in an url in the form of api/[version]/[namespace]/[call_name]/ so we would get /api/v1.0.0/math/divide/.

A valid call with the parameters {'dividend': 5, 'divisor': 2} would result in this response:

{"errors": {}, "data": 5, "success": true}

An invalid call with the parameters {'dividend': "five", 'divisor': 2} would result in this response:

{"errors": {"dividend": ["Enter a number."]}, "data": false, "success": false}

Authentication

By default APICalls have HMAC-authentication turned on. Disable it by setting signed_requests = False on your APICall.

If not disabled users of the API will have to sign their calls. To do this they need a secret generate, create a APIKey through the django admin interface. On save a personal secret and key will be generated for the API-user.

To build a call signature for the DivisonCall create a querystring of the calls parameters sorted by the keys dividend=5&divisor=2. Create a HMAC using SHA1 hash function. Example in python:

import hmac
from hashlib import sha1
hmac_sign = hmac.new(secret, urllib2.quote('dividend=5&divisor=2'), sha1).hexdigest()

A signed request against DivisionCall would have the parameters {'dividend': 5, 'divisor': 2, 'key': generated_key, 'sign': hmac_sign}

Documentation

Visit /api/discover for a brief documentation of the registered API-calls.

Comments
  • Support Python 3.4-3.6 and Django 1.7-1.10

    Support Python 3.4-3.6 and Django 1.7-1.10

    Based on #16

    Build Status

    | Django | Python 2.6 | 2.7 | 3.3 | 3.4 | 3.5 | 3.6 | | :-: | --: | --- | --- | --- | --- | --- | | 1.3 | ✅ | ✅ | | | | | | 1.4 | ✅ | ✅ | | | | | | 1.5 | ✅ | ✅ | ✅ | | | | | 1.6 | ✅ | ✅ | ✅ | | | | | 1.7 | | ✅ | ✅ | ✅ | | | | 1.8 | | ✅ | ✅ | ✅ | ✅ | ✅ | | 1.9 | | ✅ | | ✅ | ✅ | ✅ | | 1.10 | | ✅ | | ✅ | ✅ | ✅ |

    opened by andreif 6
  • The readme is broken in pypi

    The readme is broken in pypi

    The readme is broken in pypi, I think that the problem is that the underlined should have the same length that the text. You should to change this:

    Authentication
    -----
    

    For this

    Authentication
    --------------
    

    The same with Documentation.

    Congratulations for this app :-)

    opened by goinnn 2
  • Remove remaining markdown use from api/call.html template

    Remove remaining markdown use from api/call.html template

    A left-over "load markdown" tag, and use of its restructured-text filter on the docstring description were causing this view to fail since markdown dependency had been eliminated. This patch just prints the "docstring" value unformatted.

    opened by reduxionist 1
  • Run against Django 1.11 + Minor fix

    Run against Django 1.11 + Minor fix

    In addition to running against 1.11, this fixes a small issue that affects Django1.9+ where the value of the custom UUIDField does not go through formapi.utils.prepare_uuid_string on retrieval, because Django does not call to_python on assignment after deprecating SubfieldBase. The fix is to also call prepare_uuid_string on from_db_value method of the field. The added test would fail on Django >= 1.9 without overriding from_db_value,

    Not sure if it'd make more sense to use Django's own UUIDField with 1.8+ and override methods to call our prepare_uuid_string.

    opened by beshrkayali 2
  • Improved hash space and expressivity

    Improved hash space and expressivity

    Previously all random data came from Python’s built-in UUID4 encoded in hexadecimal. Hexadecimal encodes 16 values in one byte, that means there is a 4:8 ratio of meaningful bits to each byte of hexadecimal encoding. Instead we use base64 which encodes at a 6:8 ratio. This has the added benefit of looking better.

    opened by lericson 3
  • The model form are supported in the formapi and details

    The model form are supported in the formapi and details

    1. Now the model form are supported in the formapi.
    2. A simple way to pass the request to your form (request_passed)
    3. If you overwrite the get_form_kwargs method you can pass more parameters to your form
    4. And some details: reorder the imports, change API.xxx to cls.xxx or self.xxx, remove the clean method from APICall, etc
    opened by goinnn 8
Releases(0.1.0)
Owner
5 Monkeys
5 Monkeys
An airlines clone website with django

abc_airlines is a clone website of an airlines system the way it works is that first you add flights to the website then the users can search flights

milad 1 Nov 16, 2021
Visual DSL framework for django

Preface Processes change more often than technic. Domain Rules are situational and may differ from customer to customer. With diverse code and frequen

Dmitry Kuksinsky 165 Jan 08, 2023
Yet another Django audit log app, hopefully the simplest one.

django-easy-audit Yet another Django audit log app, hopefully the easiest one. This app allows you to keep track of every action taken by your users.

Natán 510 Jan 02, 2023
Use minify-html, the extremely fast HTML + JS + CSS minifier, with Django.

django-minify-html Use minify-html, the extremely fast HTML + JS + CSS minifier, with Django. Requirements Python 3.8 to 3.10 supported. Django 2.2 to

Adam Johnson 60 Dec 28, 2022
Cached file system for online resources in Python

Minato Cache & file system for online resources in Python Features Minato enables you to: Download & cache online recsources minato supports the follo

Yasuhiro Yamaguchi 10 Jan 04, 2023
Highlight the keywords of a page if a visitor is coming from a search engine.

Django-SEKH Django Search Engine Keywords Highlighter, is a middleware for Django providing the capacities to highlight the user's search keywords if

Julien Fache 24 Oct 08, 2021
Django/Jinja template indenter

DjHTML A pure-Python Django/Jinja template indenter without dependencies. DjHTML is a fully automatic template indenter that works with mixed HTML/CSS

Return to the Source 378 Jan 01, 2023
A Django app to accept payments from various payment processors via Pluggable backends.

Django-Merchant Django-Merchant is a django application that enables you to use multiple payment processors from a single API. Gateways Following gate

Agiliq 997 Dec 24, 2022
Show how the redis works with Python (Django).

Redis Leaderboard Python (Django) Show how the redis works with Python (Django). Try it out deploying on Heroku (See notes: How to run on Google Cloud

Tom Xu 4 Nov 16, 2021
Exploit Discord's cache system to remote upload payloads on Discord users machines

Exploit Discord's cache system to hide payloads PoC Remote upload embedded payload from image using EOF to Discord users machines through cache. Depen

cs 169 Dec 20, 2022
This Django app will be used to host Source.Python plugins, sub-plugins, and custom packages.

Source.Python Project Manager This Django app will be used to host Source.Python plugins, sub-plugins, and custom packages. Want to help develop this

2 Sep 24, 2022
Forgot password functionality build in Python / Django Rest Framework

Password Recover Recover password functionality with e-mail sender usign Django Email Backend How to start project. Create a folder in your machine Cr

alexandre Lopes 1 Nov 03, 2021
Atualizando o projeto APIs REST Django REST 2.0

APIs REST Django REST 3.0-KevinSoffa Atualização do projeto APIs REST Django REST 2.0-Kevin Soffa Melhorando e adicionando funcionalidades O que já fo

Kevin Soffa 2 Dec 13, 2022
Basic implementation of Razorpay payment gateway 💳 with Django

Razorpay Payment Integration in Django 💥 In this project Razorpay payment gateway 💳 is integrated with Django by breaking down the whole process int

ScaleReal 12 Dec 12, 2022
Django query profiler - one profiler to rule them all. Shows queries, detects N+1 and gives recommendations on how to resolve them

Django Query Profiler This is a query profiler for Django applications, for helping developers answer the question "My Django code/page/API is slow, H

Django Query Profiler 116 Dec 15, 2022
A drop-in replacement for django's ImageField that provides a flexible, intuitive and easily-extensible interface for quickly creating new images from the one assigned to the field.

django-versatileimagefield A drop-in replacement for django's ImageField that provides a flexible, intuitive and easily-extensible interface for creat

Jonathan Ellenberger 490 Dec 13, 2022
A package to handle images in django

Django Image Tools Django Image Tools is a small app that will allow you to manage your project's images without worrying much about image sizes, how

The Bonsai Studio 42 Jun 02, 2022
Analytics services for Django projects

django-analytical The django-analytical application integrates analytics services into a Django project. Using an analytics service with a Django proj

Jazzband 1.1k Dec 31, 2022
Use watchfiles in Django’s autoreloader.

django-watchfiles Use watchfiles in Django’s autoreloader. Requirements Python 3.7 to 3.10 supported. Django 2.2 to 4.0 supported. Installation Instal

Adam Johnson 43 Dec 14, 2022
MAC address Model Field & Form Field for Django apps

django-macaddress MAC Address model and form fields for Django We use netaddr to parse and validate the MAC address. The tests aren't complete yet. Pa

49 Sep 04, 2022