Swagger Documentation Generator for Django REST Framework: deprecated

Overview

Django REST Swagger: deprecated (2019-06-04)

This project is no longer being maintained. Please consider drf-yasg as an alternative/successor. I haven't personally used it, but it looks feature-complete and is actively maintained.

https://github.com/axnsan12/drf-yasg

Thanks for all the support and contributions over the years. Special thanks to Lights on Software, Lincoln Loop and BNOTIONS for generously donating time to work on this project ❤️ .


build-status-badge codecov pypi-version

Deploy

An API documentation generator for Swagger UI and Django REST Framework

Full documentation: http://marcgibbons.github.io/django-rest-swagger/

Installation

  1. pip install django-rest-swagger

  2. Add rest_framework_swagger to your INSTALLED_APPS setting:

        INSTALLED_APPS = (
            ...
            'rest_framework_swagger',
        )

Rendering Swagger Specification and Documentation

This package ships with two renderer classes:

  1. OpenAPIRenderer generates the OpenAPI (fka Swagger) JSON schema specification. This renderer will be presented if:
  • Content-Type: application/openapi+json is specified in the headers.
  • ?format=openapi is passed as query param
  1. SwaggerUIRenderer generates the Swagger UI and requires the OpenAPIRenderer

Quick Start Example:

from django.conf.urls import url
from rest_framework_swagger.views import get_swagger_view

schema_view = get_swagger_view(title='Pastebin API')

urlpatterns = [
    url(r'^$', schema_view)
]

Requirements

  • Django 1.8+
  • Django REST framework 3.5.1+
  • Python 2.7, 3.5, 3.6

Testing

  • Run $ tox to execute the test suite against all supported environments.
  • Run ./runtests.py to run the test suite within the current environment.

Bugs & Contributions

Please report bugs by opening an issue

Contributions are welcome and are encouraged!

Special Thanks

Many thanks to Tom Christie & all the contributors who have developed Django REST Framework

Comments
  • Add IGNORE_USER_PERMISSIONS setting

    Add IGNORE_USER_PERMISSIONS setting

    Makes it possible to ignore user permissions when generating a schema.

    I have an endpoint which lists search results (/v1/search_results/), but I'm only given access if I specify a search ID on the query string (/v1/search_results/?search=456). My code checks that the logged in user owns search 456 before allowing the user to access this endpoint.

    Without this setting, /v1/search_results/ won't appear in the generated documentation.

    opened by craiga 17
  • cigar_example documentation - RuntimeError: Unable to use callback invalid closure/function specified.

    cigar_example documentation - RuntimeError: Unable to use callback invalid closure/function specified.

    I'm using Django 1.6.2, django-rest-framework 2.3.12, and python 3.3.4

    Running the cigar_example locally errors out when trying to view the swagger documentation at http://127.0.0.1:8000/. http://127.0.0.1:8000/api/cigars/ loads properly (when including trailing slash) and the remainder of the documentation loads properly if I remove the cigars route in cigar_example/restapi/urls.py.

    The documentation page gives the error - Unable to read api 'cigars' from path http://127.0.0.1:8000/api-docs/api/cigars (server returned undefined) The stack trace is below. [08/Mar/2014 11:59:59] "GET /api-docs/ HTTP/1.1" 200 215 Internal Server Error: /api-docs/api/cigars Traceback (most recent call last): File "D:\Development\virtualenv\aws-django\lib\site-packages\django\core\handlers\base.py", line 114, in get_response response = wrapped_callback(request, _callback_args, *_callback_kwargs) File "D:\Development\virtualenv\aws-django\lib\site-packages\django\views\generic\base.py", line 69, in view return self.dispatch(request, _args, *_kwargs) File "D:\Development\virtualenv\aws-django\lib\site-packages\django\views\decorators\csrf.py", line 57, in wrapped_view return view_func(_args, *_kwargs) File "D:\Development\virtualenv\aws-django\lib\site-packages\rest_framework\views.py", line 399, in dispatch response = self.handle_exception(exc) File "D:\Development\virtualenv\aws-django\lib\site-packages\rest_framework\views.py", line 396, in dispatch response = handler(request, _args, *_kwargs) File "D:\Development\virtualenv\aws-django\lib\site-packages\rest_framework_swagger\views.py", line 84, in get 'apis': generator.generate(apis), File "D:\Development\virtualenv\aws-django\lib\site-packages\rest_framework_swagger\docgenerator.py", line 21, in generate 'operations': self.get_operations(api), File "D:\Development\virtualenv\aws-django\lib\site-packages\rest_framework_swagger\docgenerator.py", line 41, in get_operations for method_introspector in introspector: File "D:\Development\virtualenv\aws-django\lib\site-packages\rest_framework_swagger\introspectors.py", line 285, in iter methods = self._resolve_methods() File "D:\Development\virtualenv\aws-django\lib\site-packages\rest_framework_swagger\introspectors.py", line 294, in _resolve_methods raise RuntimeError('Unable to use callback invalid closure/function specified.') RuntimeError: Unable to use callback invalid closure/function specified. [08/Mar/2014 11:59:59] "GET /api-docs/api/manufacturers HTTP/1.1" 200 3514 [08/Mar/2014 11:59:59] "GET /api-docs/api/custom HTTP/1.1" 200 931 [08/Mar/2014 11:59:59] "GET /api-docs/api/countries HTTP/1.1" 200 2694 [08/Mar/2014 12:00:00] "GET /api-docs/api/cigars HTTP/1.1" 500 122324

    opened by sdg9 17
  • Docstring parser powered by YAML

    Docstring parser powered by YAML

    This parser allows you override some parts of automatic method inspection behaviours which are not always correct. Also you may style your documentation with Markdown syntax.

    Docstring parser powered by YAML syntax

    This parser allows you override some parts of automatic method inspection
    behaviours which are not always correct.
    
    See the following documents for more information about YAML and Swagger:
    - https://github.com/wordnik/swagger-core/wiki
    - http://www.yaml.org/spec/1.2/spec.html
    - https://github.com/wordnik/swagger-codegen/wiki/Creating-Swagger-JSON-from-YAML-files
    
    1. Control over parameters
    ============================================================================
    Define parameters and its properties in docstrings:
    
        parameters:
            - name: some_param
              description: Foobar long description goes here
              required: true
              type: integer
              paramType: form
              minimum: 10
              maximum: 100
            - name: other_foo
              paramType: query
            - name: avatar
              type: file
    
    It is possible to override parameters discovered by method inspector by
    defining:
        `parameters_strategy` option to either `merge` or `replace`
    
    To define different strategies for different `paramType`'s use the
    following syntax:
        parameters_strategy:
            form: replace
            query: merge
    
    By default strategy is set to `merge`
    
    
    Sometimes method inspector produces wrong list of parameters that
    you might not won't to see in SWAGGER form. To handle this situation
    define `paramTypes` that should be omitted
        omit_parameters:
            - form
    
    2. Control over serializers
    ============================================================================
    Once in a while you are using different serializers inside methods
    but automatic method inspector cannot detect this. For that purpose there
    is two explicit parameters that allows you to discard serializer detected
    by method inspector OR replace it with another one
    
        serializer: some.package.FooSerializer
        omit_serializer: true
    
    3. Custom Response Class
    ============================================================================
    If your view is not using serializer at all but instead outputs simple
    data type such as JSON you may define custom response object in method
    signature like follows:
    
        type:
          name:
            required: true
            type: string
          url:
            required: false
            type: url
    
    4. Response Messages (Error Codes)
    ============================================================================
    If you'd like to share common response errors that your APIView might throw
    you can define them in docstring using following format:
    
    responseMessages:
        - code: 401
          message: Not authenticated
        - code: 403
          message: Insufficient rights to call this procedure
    
    
    5. Different models for reading and writing operations
    ============================================================================
    Since REST Framework won't output write_only fields in responses as well as
    does not require read_only fields to be provided it is worth to
    automatically register 2 separate models for reading and writing operations.
    
    Discovered serializer will be registered with `Write` or `Read` prefix.
    Response Class will be automatically adjusted if serializer class was
    detected by method inspector.
    
    You can also refer to this models in your parameters:
    
    parameters:
        - name: CigarSerializer
          type: WriteCigarSerializer
          paramType: body
    
    
    SAMPLE DOCSTRING:
    ============================================================================
    
    ---
    # API Docs
    # Note: YAML always starts with `---`
    
    type:
      name:
        required: true
        type: string
      url:
        required: false
        type: url
      created_at:
        required: true
        type: string
        format: date-time
    
    serializer: .serializers.FooSerializer
    omit_serializer: false
    
    parameters_strategy: merge
    omit_parameters:
        - path
    parameters:
        - name: name
          description: Foobar long description goes here
          required: true
          type: string
          paramType: form
        - name: other_foo
          paramType: query
        - name: other_bar
          paramType: query
        - name: avatar
          type: file
    
    responseMessages:
        - code: 401
          message: Not authenticated
    

    I've also added URL grouping and Token authentication from other PR's (credits goes there).

    opened by pySilver 17
  • How to use the new version (2+) with TokenAuthentication?

    How to use the new version (2+) with TokenAuthentication?

    As far as I understand, the way to include the TokenAuthentication is use the SECURITY_DEFINITIONS settings.

    In the OpenAPI Docs, in the "api_key" type, there are 3 keys: "type", "name", "in".

    I guess that "in" should be "header", name "Authorization" and type should be left "apiKey". Where should I put the value "Token MYTOKEN"?

    This ticket may be related to #497 , but I'm not sure.

    Thanks in advance

    opened by duduklein 16
  • problem of using swagger when I use the get_serializer_class() for dynamic serializer based on the URL's charges

    problem of using swagger when I use the get_serializer_class() for dynamic serializer based on the URL's charges

    I am using django-rest-swagger for api doc generation. I would like to return different user the different part of models. So I used the get_serializer_class() function to use different serializer for different users by checking the kwargs['pk'] on the url.

    The urls.py is:

    url(r'^api/users/$', views.UserEnum.as_view()),
    url(r'^api/users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),
    

    The view that I am using is:

    #List all the users or create a new user
    class UserEnum(generics.ListCreateAPIView):
        queryset = User.objects.all()
        serializer_class = UserSerializer
        permission_classes = (IsAuthenticated, IsAdminUser,)
    
    class UserDetail(generics.RetrieveUpdateDestroyAPIView):
        queryset = User.objects.all()
        #serializer_class = UserSerializer #TODO: Problem with Swagger
        permission_classes = (IsAuthenticated, IsOwnerAdminOrReadOnly,)
    
        def get_serializer_class(self):
            #swagger crash here.
            user_id = int(self.kwargs['pk'])
            if self.request.user.id == user_id or self.request.user.is_superuser:
                serializer_class = UserSerializer
            else:
                serializer_class = UserProfileSerializer
            return serializer_class
    
        def get_object(self, *args, **kwargs):
            user_id = int(self.kwargs['pk'])
    
            if self.request.user.id == user_id or self.request.user.is_superuser:
                return User.objects.get(id=user_id)
            else:
                return UserProfile.objects.get(user=user_id)
    

    The above two urls work successfully without problems. But when I type the http://127.0.0.1:8000/api/ for generate api docs, it return the below error:

    `Unable to read api 'users' from path http://127.0.0.1:8000/api/api-docs/api/users (server returned Internal Server Error)`
    
    
    File "/Users/Scofield/anaconda/lib/python2.7/site-packages/rest_framework_swagger/introspectors.py" in ask_for_serializer_class
      179.                 return view.get_serializer_class()
    File "/Users/Scofield/Dropbox/My Projects/Angels&Demons/src/doWishSites/doWishCore/views.py" in get_serializer_class
      27.         user_id = int(self.kwargs['pk'])
    
    Exception Type: KeyError at /api/api-docs/api/users
    Exception Value: 'pk'
    
    opened by gufeisun 16
  • Group list_route with viewset base path

    Group list_route with viewset base path

    I have PhotosViewSet with list and list_route upload action. I would like it to see under same 'photos' group in the docs. image

    What i am doing wrong? Is it supported?

    for method in self.get_allowed_methods(callback):
        key = self.get_key(path, method, callback)
    

    in SchemaGenerator get_key seems to not take 'list route' actions into account.

    django-rest-framework 
    opened by vladimirnani 15
  • Use latest swagger-ui

    Use latest swagger-ui

    It looks like the version of swagger-api/swagger-ui that is in use by django-rest-swagger is quite old. From what I can see it looks like it's based on 2.0.17. Is there a reason it hasn't been updated? Would a PR updating to the latest be likely to be accepted? I see there have been a few changes made manually to the JS and CSS, but those changes could probably be re-applied if necessary.

    opened by rygwdn 15
  • Method docstrings not included in generated docs

    Method docstrings not included in generated docs

    I recently upgraded from 0.3.5 to 2.0.4. Previously, docstrings on view methods (MyView.get) would be included in the swagger generated docs, but with the new version I don't get any docs included. It does seem to introspect serializer fields and such, but the docstrings help users of the API understand what an endpoint does and when to use it. Is there any way to get those included with the current release?

    django-rest-framework 
    opened by jwineinger 13
  • Django Swagger shown HTTP Error 500 and not processed HTML code when accessing without logged in user

    Django Swagger shown HTTP Error 500 and not processed HTML code when accessing without logged in user

    • Current versions installed in my app:

    django-rest-swagger==2.0.1 djangorestframework==3.4.0

    • Brief configuration:

    -- urls.py --

    router = DefaultRouter()
    router.register(r'documents', DocumentViewSet)
    router.register(r'bounces', BounceViewSet)
    router.register(r'users', UserViewSet)
    
    #DOC SWAGGER API
    url(r'^documentacion/$', esquema_doc_api),
    
    

    -- views.py --

    @api_view()
    @renderer_classes([SwaggerUIRenderer, OpenAPIRenderer])
    def esquema_doc_api(request):
        generator = schemas.SchemaGenerator(title='TEST API')
        return response.Response(generator.get_schema(request=request))
    
    

    -- development server petitions log -- [19/Jul/2016 09:36:00] "GET /documentacion/?format=openapi HTTP/1.1" 500 83970

    Now if I launch my project and type http://ip:port/documentacion/ in my browser I get an HTTP error 500 and display raw HTML content inside my Swagger view. The problem disappears when I use a logged in user. Anyway when l use a logged in user I still can see and endpoint with the same name that my scheme creator function 'esquema_doc_api' and returns HTML when I fire the GET method on it. I'm not pretty sure if it's supposed to be the standard behaviour.

    I'll attach some screenshot with the problem.

    Regards,

    Javier Civantos

    swagger_not_logged swagger_logged

    django-rest-framework 
    opened by civantos 13
  • A less naive strategy for getting view closure var

    A less naive strategy for getting view closure var

    • Handles a particular class of decorated view functions that refer to the outermost closure arguments.
    • Searches for a types.FunctionType argument in the closure, rather than assuming the first argument is the view. This is a correct implementation for existing cases as well.
    opened by mverteuil 12
  • fbv failes with Exception: methods ['serializer'] in class docstring are not in view methods [u'OPTIONS', u'GET']

    fbv failes with Exception: methods ['serializer'] in class docstring are not in view methods [u'OPTIONS', u'GET']

    The following documentation raised the error.

    """
        ---
        serializer: MySerializer
    """
    

    Had to change docgenerator.py:42 from:

            if str(callback) == \
                    "<class 'rest_framework.decorators.WrappedAPIView'>":
    

    to

            if str(callback).startswith("<class 'rest_framework.decorators."):
    

    This also reproduces for the example project and doesn't seem to be tested.

    opened by f3r3nc 12
  • Update index.html

    Update index.html

    {% load staticfiles %} and {% load admin_static %} were deprecated in Django 2.1, and removed in Django 3.0. I propose to change it with {% load static %}

    opened by sjtly16 0
  • request: add option to remove the need to click

    request: add option to remove the need to click "try it out"

    My main usage of the swagger docs is to try things with the API. It would be nice if we could disable the "Try it out" button and just have the form enabled by default so you save some pointing and clicking before you can try out a request. Or multiple requests.

    opened by valentijnscholten 1
  • change staticfiles tag to static

    change staticfiles tag to static

    The index.html file in the templates folder contains a load "staticfiles" import which I assume is for using the static tag.

    However, this returns an error since this isn't the load command django recommends for static files. Hence, I changed:

    {% load staticfiles %}

    to

    {% load static %}.

    After this, it no longer throws the error of not recognizing the load staticfiles import.

    opened by marvelous-ikechi 2
Releases(2.2.0)
  • 2.2.0(Apr 30, 2018)

    • Update Swagger UI to version 3.13.6
    • Bootstrap client app to extend UI components in React (to improve auth functionality in the future for non-session APIs)
    • Ability to customize headers; eventually will want to do this from the UI as well
    Source code(tar.gz)
    Source code(zip)
  • 2.1.0(Oct 29, 2016)

  • 2.0.2(Jul 20, 2016)

    • Update Swagger UI and remove trailing styles.css (Fixes #487)
    • Remove 1.10 deprecation warning from render method
    • Update Manifest to exclude bytecode, include license and readme in dist.
    Source code(tar.gz)
    Source code(zip)
  • 2.0.0a0(Jul 14, 2016)

    • Breaking version change; accompanying Django REST Framework 3.4 and CoreAPI
    • Deprecation of introspection & YAML overrides
    • Use renderer classes to generate spec and UI
    Source code(tar.gz)
    Source code(zip)
Owner
Marc Gibbons
Full stack dev. Specialist in Django, REST APIs, Vue JS. Test-obsessed.
Marc Gibbons
Automated generation of real Swagger/OpenAPI 2.0 schemas from Django REST Framework code.

drf-yasg - Yet another Swagger generator Generate real Swagger/OpenAPI 2.0 specifications from a Django Rest Framework API. Compatible with Django Res

Cristi Vîjdea 3k Dec 31, 2022
Flask-Rebar combines flask, marshmallow, and swagger for robust REST services.

Flask-Rebar Flask-Rebar combines flask, marshmallow, and swagger for robust REST services. Features Request and Response Validation - Flask-Rebar reli

PlanGrid 223 Dec 19, 2022
A curated list of awesome tools for Sphinx Python Documentation Generator

Awesome Sphinx (Python Documentation Generator) A curated list of awesome extra libraries, software and resources for Sphinx (Python Documentation Gen

Hyunjun Kim 831 Dec 27, 2022
Literate-style documentation generator.

888888b. 888 Y88b 888 888 888 d88P 888 888 .d8888b .d8888b .d88b. 8888888P" 888 888 d88P" d88P" d88""88b 888 888 888

Pycco 808 Dec 27, 2022
Documentation generator for C++ based on Doxygen and mosra/m.css.

mosra/m.css is a Doxygen-based documentation generator that significantly improves on Doxygen's default output by controlling some of Doxygen's more unruly options, supplying it's own slick HTML+CSS generation and adding a fantastic live search feature.

Mark Gillard 109 Dec 7, 2022
Markdown documentation generator from Google docstrings

mkgendocs A Python package for automatically generating documentation pages in markdown for Python source files by parsing Google style docstring. The

Davide Nunes 44 Dec 18, 2022
SqlAlchemy Flask-Restful Swagger Json:API OpenAPI

SAFRS: Python OpenAPI & JSON:API Framework Overview Installation JSON:API Interface Resource Objects Relationships Methods Custom Methods Class Method

Thomas Pollet 361 Nov 16, 2022
A swagger tool for tornado, using python to write api doc!

SwaggerDoc About A swagger tool for tornado, using python to write api doc! Installation pip install swagger-doc Quick Start code import tornado.ioloo

aaashuai 1 Jan 10, 2022
Sane and flexible OpenAPI 3 schema generation for Django REST framework.

drf-spectacular Sane and flexible OpenAPI 3.0 schema generation for Django REST framework. This project has 3 goals: Extract as much schema informatio

T. Franzel 1.4k Jan 8, 2023
Generating a report CSV and send it to an email - Python / Django Rest Framework

Generating a report in CSV format and sending it to a email How to start project. Create a folder in your machine Create a virtual environment python3

alexandre Lopes 1 Jan 17, 2022
Main repository for the Sphinx documentation builder

Sphinx Sphinx is a tool that makes it easy to create intelligent and beautiful documentation for Python projects (or other documents consisting of mul

null 5.1k Jan 2, 2023
API Documentation for Python Projects

API Documentation for Python Projects. Example pdoc -o ./html pdoc generates this website: pdoc.dev/docs. Installation pip install pdoc pdoc is compat

mitmproxy 1.4k Jan 7, 2023
Main repository for the Sphinx documentation builder

Sphinx Sphinx is a tool that makes it easy to create intelligent and beautiful documentation for Python projects (or other documents consisting of mul

null 5.1k Jan 4, 2023
Project documentation with Markdown.

MkDocs Project documentation with Markdown. View the MkDocs documentation. Project release notes. Visit the MkDocs wiki for community resources, inclu

MkDocs 15.6k Jan 2, 2023
Watch a Sphinx directory and rebuild the documentation when a change is detected. Also includes a livereload enabled web server.

sphinx-autobuild Rebuild Sphinx documentation on changes, with live-reload in the browser. Installation sphinx-autobuild is available on PyPI. It can

Executable Books 440 Jan 6, 2023
Your Project with Great Documentation.

Read Latest Documentation - Browse GitHub Code Repository The only thing worse than documentation never written, is documentation written but never di

Timothy Edmund Crosley 809 Dec 28, 2022
:blue_book: Automatic documentation from sources, for MkDocs.

mkdocstrings Automatic documentation from sources, for MkDocs. Features Python handler features Requirements Installation Quick usage Features Languag

Timothée Mazzucotelli 1.1k Dec 31, 2022
Run `black` on python code blocks in documentation files

blacken-docs Run black on python code blocks in documentation files. install pip install blacken-docs usage blacken-docs provides a single executable

Anthony Sottile 460 Dec 23, 2022
:blue_book: Automatic documentation from sources, for MkDocs.

mkdocstrings Automatic documentation from sources, for MkDocs. Features - Python handler - Requirements - Installation - Quick usage Features Language

null 1.1k Jan 4, 2023