JSON API should be as simple as `dict` and status code :)
Project description
django-raw-api
JSON API should be as simple as dict
and status code :)
Hello world
from raw_api import validate_json
@validate_json({"name": str})
def hello(request):
name = request.json["name"]
if name == "world":
return "won't work here", 400
return {"hello": name}
Setup
- Install in from pypi:
pip install django-raw-api
- Add
raw_api.middleware
middleware intoMIDDLEWARE
list of yoursettings.py
API
Middleware
It adds lazy request.json
attribute and serializes raw responses such as:
str
or tuple(message: str, status: int)
- into plain text responsedict
or(data: dict, status: int)
- into JSON response
Request
request.json
- parsed jsonrequest.query
- parsed query (only after@validate_query
)
Response
You can just return str
, dict
with an optional status code
def hello(request):
return "hi"
def hello_json(request):
return {"hello": "world"}
def with_status(request):
return {"message": "bad request"}, 400
Auth
Decorators @user_required
and @staff_required
is analogous to
@login_required
and @staff_member_required
with JSON output instead of
redirecting
from raw_api import staff_required
@staff_required
async def hello(request):
return {"admin": "zone"}
Data validation
@validate_query
and @validate_json
decorators are there to perform simple
first-level validation of requests data. Internally they use the trafaret
library.
from raw_api import validate_json, validate_query
@validate_json({"ids": [int], "hello?": str})
async def foo(request):
return request.json
@validate_query({"id": int})
async def bar(request):
assert isinstance(id, int)
return request.query
Tests
python -m venv .venv
source .venv/bin/activate
pip install -Ur requirements-dev.txt
python -m pytest tests
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distributions
No source distribution files available for this release.See tutorial on generating distribution archives.
Built Distribution
Close
Hashes for django_raw_api-0.3.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 73fa678d1501953aea0233a0a672e133e297bb810c21ac9ef36cfc64671e87e6 |
|
MD5 | d2bfcd9a24e15116669d9d4dab46cc95 |
|
BLAKE2b-256 | cb1961530cffdea31a4b95ed30fb303f114bd8f9aa0fd4b91a38b815488c28cc |