Git Product home page Git Product logo

django-restless's Introduction

Django Restless

Build Status Coverage Status PyPi version

Django Restless is a lightweight set of tools for implementing JSON-based RESTful APIs in Django. It helps with writing APIs that loosely follow the RESTful paradigm, without forcing you to do so, and without imposing a full-blown REST framework.

Restless provides only JSON support. If you need to support XML or other formats, you probably want to take a look at some of the other frameworks out there (we recommend Django REST framework).

Here is a simple view implementing an API endpoint greeting the caller:

from restless.views import Endpoint

class HelloWorld(Endpoint):
    def get(self, request):
        name = request.params.get('name', 'World')
        return {'message': 'Hello, %s!' % name}

One of the main ideas behind Restless is that it's lightweight and reuses as much of functionality in Django as possible. For example, input parsing and validation is done using standard Django forms. This means you don't have to learn a whole new API to use Restless.

Installation

Django Restless is available from cheeseshop, so you can install it via pip:

pip install DjangoRestless

For the latest and the greatest, you can also get it directly from git master:

pip install -e git+ssh://github.com/senko/DjangoRestless/tree/master

The supported Python versions are 2.6, 2.7, 3.3 and 3.4, and the supported Django versions are 1.5+.

Documentation

Documentation is graciously hosted by ReadTheDocs: http://django-restless.rtfd.org/

License

Copyright (C) 2012-2015 by Django Restless contributors. See the AUTHORS file for the list of contributors.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

django-restless's People

Contributors

aljosa avatar denibertovic avatar dimlev avatar ihabunek avatar itoldya avatar mcallistersean avatar senko avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-restless's Issues

Support for limiting (or expanding) response fields

It'd be really neat to request an endpoint and specify which fields I'd like back in the request, which may help keep size down if you know you only need a few fields.

I've not found a great way to do this yet, but I've got a few ideas around keeping a root serialize dict, and index into that for the values of a serialize call, defaulting to a list of default fields to include. Sounds a bit heavy-handed.

Anyone have better ideas or solutions?

Add pagination helpers

Django's built-in paginator works in terms of fixed-size pages. While usable in API context, this might pose problems if results are likely to change between subsequent page requests (eg. more data pours in).

A simple pagination model with since (all objects after the selected one) and limit works better in this case. Here's a sample implementation:

def get_paginated_data(data, start, count, order='-id'):
    if order.startswith('-'):
        asc = False
        order_field = order[1:]
    else:
        asc = True
        order_field = order

    ordered_data = data.order_by(order)
    if start:
        filter_fields = {
            order_field + ('__gte' if asc else '__lte'): start
        }
        ordered_data = ordered_data.filter(**filter_fields)

    retval = list(ordered_data[:count + 1])
    if len(retval) > count:
        obj = retval[count]
        while '__' in order_field:
            prefix, order_field = order_field.split('__', 1)
            obj = getattr(obj, prefix)
        next = getattr(obj, order_field)
        retval = retval[:-1]
    else:
        next = None

    return (retval, next)

Note that this example includes the "since" object in results (in effect, returning it twice).

Wrong content type header in JSONResponse

I just ran into a bug with 0.0.6 and a client machine using IE9.

It seems IE9 doesn't like the "application/json; charset=utf8" content type header and drops the response data (without warning).
Not sure what the correct way to handle this is, but changing the header to read "application/json; charset=utf-8" (notice the dash) makes it work again.
This also seems to be the correct way of doing it, see http://www.w3.org/International/O-HTTP-charset.en
Since it's just a one character fix in http.py, I didn't issue a pull request.

Add HATEOAS features

It'd be good to have some form of self-describing API, in terms of providing list (and possibly descriptions) of available resources.

multipart payload TEST not working on Django 1.10.6

`--> pip freeze
alabaster==0.7.10
Babel==2.3.4
coverage==4.3.4
Django==1.10.6
docutils==0.13.1
flake8==3.3.0
imagesize==0.7.1
Jinja2==2.9.5
MarkupSafe==0.23
mccabe==0.6.1
pycodestyle==2.3.1
pyflakes==1.5.0
Pygments==2.2.0
pytz==2016.10
requests==2.13.0
six==1.10.0
snowballstemmer==1.2.1
Sphinx==1.5.3
`--> python3 manage.py test --failfast
Creating test database for alias 'default'...
................F
======================================================================
FAIL: test_create_author_multipart (testapp.tests.TestEndpoint)
Exercise multipart/form-data POST
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/cleber/code/third-party/django-restless/testproject/testapp/tests.py", line 346, in test_create_author_multipart
    self.assertEqual(r.status_code, 201, r.content)
AssertionError: 400 != 201 : b'{"error": "invalid author data", "details": {"name": ["This field is required."]}}'

I made a slight modification on asserEqual so it could print r.content. Aparently, although name is indeed being present on the payload (see below), it's not being recognized somewhere.

The test:

    def test_create_author_multipart(self):    
        """Exercise multipart/form-data POST"""    
    
        r = self.client.post('author_list', data={    
            'name': 'New User',    
        })  # multipart/form-data is default in test client    
        self.assertEqual(r.status_code, 201, r.content)    
        self.assertEqual(r.json['name'], 'New User')    
        self.assertEqual(r.json['name'],    
                         Author.objects.get(id=r.json['id']).name)

`fields` has to be a list if combined with `include`

Not sure what approach you'd want to handle this, but if you pass in fields as a tuple and include too, then you get AttributeError: 'tuple' object has no attribute 'append'.

The approaches I can think of would be:

  1. document that fields has to be a list (not very pythonic)
  2. make sure fields is a list (extra code)
  3. raise some sort of error that fields has to be a list (not very pythonic and extra code)

relevant code in serialize_model:

    if include is not None:
        for i in include:
            if isinstance(i, tuple) or (isinstance(i, six.string_types)):
                fields.append(i)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.