Giter VIP home page Giter VIP logo

django-rest-framework-docs's Introduction

** This package is no longer being maintained **

=========================== Rest Framework Docs (0.1.7)

Rest Framework Docs is an application built to produce an inventory and documentation for your Django Rest Framework v2 endpoints.

Installation

From pip:

pip install django-rest-framework-docs

From the source:

Quick start

  1. Add "rest_framework_docs" to your INSTALLED_APPS setting like this:

        INSTALLED_APPS = (
            ...
            'rest_framework_docs',
        )
  2. Include the polls URLconf in your project urls.py like this:

        url(r'^rest-api/', include('rest_framework_docs.urls')),
  1. View /rest-api/ to see your Django Rest Framework endpoints

Requirements

  • Django [1.4, 1.5]
  • Django Rest Framework (2.1, 2.2, 2.3)

How it works

The Django Rest Framework Docs scans your projects URL patterns for endpoints inheriting from Django Rest Framework views. It extracts comments, variables and methods from your code to generate documentation. Here is what is being tracked to generate documentation:

  1. The name attribute from the URL pattern is used as the title. The following will produce a title of 'List of Countries'
      url(r'^api/countries/?$', views.Countries.as_view(), name='list_of_countries'),
  1. The class doctsring is used as the description:
    class Countries(APIView):
    """
    This text is the description for this API
    """
  1. The class model. (ie. User)

  2. Allowed methods (GET, POST, PUT, etc.)

  3. Serializer properties. If your API uses a serializer, the properties are listed

  4. Custom parameters. It is possible to customize a parameter list for your API. To do so, include a key-value pair in the docstring of your API class delimited by two hyphens ('--'). Example: 'start_time -- The first reading':

    class Countries(APIView):
        """
        This text is the description for this API
        param1 -- A first parameter
        param2 -- A second parameter
        """

Customization

Template

Django REST Framework Docs comes with a default template which you may override.

Make an API

Another option is to create an API for documentation that can be consumed on a different platform (ie. mobile).

        import json
        from rest_framework.response import Response
        from rest_framework.views import APIView
        from cigar_example.restapi import urls
        from rest_framework_docs.docs import DocumentationGenerator


        class ApiDocumentation(APIView):
            """
            Gets the documentation for the API endpoints
            """
            def get(self, *args, **kwargs):
                docs = DocumentationGenerator().get_docs()
                return Response(json.loads(docs))

Specify your own URL patterns

By default, Django REST Framework Docs scans all your URL patterns and extracts those which inherit from the base rest_framework.views.APIView. You may choose to explicitly specify which URL patterns are to be included in the documentation by providing the urlpatterns to the DocumentationGenerator constructor.

    from yourproject.myapp import urls
    docs = DocumentationGenerator(urls.urlpatterns).get_docs()

Included Example

Included is an example project called cigar_example. It contains both Model-based and custom API views to demonstrate the different behaviours. I also included an API of the documentation, that is, the data parsed by the generator in JSON format (api/docs). Screenshot ApiInception

Contributions

Please contribute to improve this tool!

Special Thanks

Many thanks to Tom Christie for developing the Django Rest Framework - a tool I use everyday.

Release Notes

v.0.1.7 (Sept 5, 2013)

  • Added filtering & ordering
  • URL flattening & custom serializer fixes

v.0.1.6 (June 5, 2013)

  • Bugfix when url patterns property 'name' is None

v.0.1.5 (June 1, 2013)

  • Now supports Django Rest Framework v2.3
  • Backwards compatibility

v.0.1.4 (April 3, 2013)

  • Improved URL importing: included URL modules now show the full URL with prefix
  • Borrowing URL "restification" from Django's admin docs
  • General refactoring
  • Wrote a few tests, more need to be written

v.0.1.3 (March 6, 2013)

  • URL import bug resolved

v.0.1.2 (Feb 14, 2013)

  • Now possible to use URL patterns using include Example: (r'', include('project.some_app.urls')),

v0.1.1 (Jan 24, 2013)

  • Fixed trailing $ sign in the URL pattern regex
  • Changed URL pattern to show docs at index
  • Added example Django REST application called cigar_example.
  • Minor CSS changes
  • Fixed setup.py requirements to require django>=1.4
  • Fixed extra spaces in serializer fields regex (ie. U R L => URL)

Contributors

  • Marc Gibbons (@marcgibbons)
  • Scott Mountenay (@scottmx81)
  • @swistakm
  • Peter Baumgartner (@ipmb)
  • Marlon Bailey (@avinash240)
  • @filipeximenes
  • @pleasedontbelong

License

Copyright (c) 2013, Marc Gibbons All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

django-rest-framework-docs's People

Contributors

fernandogrd avatar filipeximenes avatar ipmb avatar marcgibbons avatar pleasedontbelong avatar swistakm 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  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-rest-framework-docs's Issues

"Expected string or buffer" bug

Immediately after following configuration instructions, I tried loading the main page, but encountered the following error screen.

rest_framework version: 2.3.4

TypeError at /
expected string or buffer
Request Method: GET
Request URL: http://localhost:8000/
Django Version: 1.5.1
Exception Type: TypeError
Exception Value:
expected string or buffer
Exception Location: /usr/lib/python2.7/re.py in sub, line 151
Python Executable: /usr/bin/python
Python Version: 2.7.4
Python Path:
['/home/alex/workspace/Masters/Fingerprints_django',
'/home/alex/workspace/Masters/Fingerprints_django',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages/PILcompat',
'/usr/lib/python2.7/dist-packages/gst-0.10',
'/usr/lib/python2.7/dist-packages/gtk-2.0',
'/usr/lib/pymodules/python2.7',
'/usr/lib/python2.7/dist-packages/ubuntu-sso-client',
'/usr/lib/python2.7/dist-packages/ubuntuone-client',
'/usr/lib/python2.7/dist-packages/ubuntuone-control-panel',
'/usr/lib/python2.7/dist-packages/ubuntuone-couch',
'/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol',
'/usr/lib/python2.7/dist-packages/wx-2.8-gtk2-unicode']
Server time: Wed, 5 Jun 2013 18:00:15 +1000

Might make more sense to have the docs URL as the index.

It's not immediately obvious that when you include it in the URL conf using...

url(r'^rest-api/', include('rest_framework_docs.urls')),

That the docs endpoint is actually...

rest-api/docs/

It might(?) be better to have the docs view at the index, so it's simply hosted at:

rest-api/

What do you think?

Add an image to the README as an example.

Tried this out now and was really pleased with how it looks. :) Would be really great if the README included an image to give an example of what this looks like when installed, so it's clear that it really does give you a nice docs interface.

'URLField' -> 'U R L Field'

Noticed that for fieldnames like URLField, the splitting get applied incorrectly, leading to the field being listed as 'U R L Field' (eg. as in the screenshot you've given)

There's a similar bit of code in REST framework do deal with translating view classes to names for the browseable API, which uses a regex which has marginally more correct behavior, which you might (or might not) want to reuse...

>>> import re
>>> field_name = 'URLField'
>>> CAMELCASE_BOUNDARY = '(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))'
>>> print re.sub(CAMELCASE_BOUNDARY, ' \\1', field_name).strip()
URL Field

Disclaimer: Nope, I really don't remember exactly how that regex works. Black magic. :)

Formatting of docstrings

Hi,

This is a feature request more than an issue, I suppose, but I was wondering if it would be possible to chuck 'pre' tags around docstrings to preserve formatting.

In particular, I'd like to be able to provide examples of some of my custom JSON messages, but they get mashed into a single line.

An (better?) alternative would be to support Markdown syntax in docstrings, but I feel that simply marking the content as preformatted would go a long way, and perhaps be more general (much as I love Markdown, participants in larger projects may have already picked a different kind of formatting for other reasons).

As a side note, the doc fields on the param parameters are truncated if they contain line breaks, but I guess that's a reasonable restriction.

PS. I thought I'd posted this a few days ago but I guess I forgot to press Submit! And thanks for the great code.

request attribute is not set in views

request attribute is not set in views while generating documentation so if you some custom methods accessing self.request it raises an AttributeError:
'MyAPIView' object has no attribute 'request'.

In my project, I access self.request overriding get_serializer_class and I have the following stacktrace:

Traceback:
File "[...]/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "[...]/local/lib/python2.7/site-packages/rest_framework_docs/views.py" in documentation
  7.     docs = DocumentationGenerator().get_docs(as_objects=True)
File "[...]/local/lib/python2.7/site-packages/rest_framework_docs/docs.py" in get_docs
  36.         docs = self.__process_urlpatterns()
File "[...]/local/lib/python2.7/site-packages/rest_framework_docs/docs.py" in __process_urlpatterns
  128.             doc.fields = self.__get_serializer_fields__(callback)
File "[...]/local/lib/python2.7/site-packages/rest_framework_docs/docs.py" in __get_serializer_fields__
  220.             serializer = callback().get_serializer_class()
File "[...]/local/lib/python2.7/site-packages/myproject/api/views.py" in get_serializer_class
  170.         if self.request.method == 'POST':

Reuse django.contrib.admindocs code

There's some stuff in django.contrib.admindocs that might be useful for you. In particular, the utils module can handle trimming and parsing the docstring instead of writing your own. It also handles parsing as reST which would be a nice feature.

Add support for ViewSets

django-rest-framework-docs can't see ViewSet classes because they don't inherit from APIView.
It would be great to generate the doc from the methods marked with @link and @action

Add an option to filter api urls in DocumentGenerator

Maybe using django url namespace? It could be parameter of .get_docs method. It would be nice feature to have separate docs for different versions of API and I think that using different namespaces for different API versions is good way to achieve this.

There could be also other kinds of filters e.g. regex.

AtrributeError module' object has no attribute 'urls'

Was looking into this to try out encode/django-rest-framework/pull/616 and it doesn't wrok in my project. I think the problem comes from the fact that the ROOT_URLCONF setting may or may not be the place you want to import from. See the django docs for info. Could be something totally unrelated though.

In this project I have ROOT_URLCONF='urls' but I get:

Exception Type: AttributeError
Exception Value:    'module' object has no attribute 'urls'

If I change docs.py to:

    urls = __import__(settings.ROOT_URLCONF)
    patterns = urls.urlpatterns # <- changed

…it works (but all of the later calls to class_instance = pattern.callback.cls_instance raise an exception and I get a blank page.)

Trailing / not shown in URLs

URL patterns such as:

r'^users/$'

are shown as:

/users

The trailing slash should be shown β€” it's a required part of the URL.

This issue seems maybe related to #3 at first glance. There wasn't a link to the fixing commit so I can't say more right now.

Request not sent via https

When i send a request from https site, the request URL is generated with http protocol and browser doesn't execute it, because mixing content is depricated. How can i solve this?

Thank you.

django.utils.importlib deprecated in Django 1.7

Django doc says django.utils.importlib deprecated in Django 1.7

https://docs.djangoproject.com/en/1.7/releases/1.7/#features-deprecated-in-1-7

File "/Users/user/some/directory/project/project/urls.py", line 12, in <module>
   url(r'^api/docs/v1/', include('rest_framework_docs.urls')),
 File "/Users/user/.virtualenvs/venv/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 52, in include
   urlconf_module = import_module(urlconf_module)
 File "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
   __import__(name)
 File "/Users/user/.virtualenvs/venv/lib/python2.7/site-packages/rest_framework_docs/urls.py", line 2, in <module>
   from views import documentation
 File "/Users/user/.virtualenvs/venv/lib/python2.7/site-packages/rest_framework_docs/views.py", line 1, in <module>
   from docs import DocumentationGenerator
 File "/Users/user/.virtualenvs/venv/lib/python2.7/site-packages/rest_framework_docs/docs.py", line 4, in <module>
   from django.utils.importlib import import_module

ImportError: No module named importlib

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.