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
Country-specific Django helpers, to use in Django Rest Framework

django-rest-localflavor Country-specific serializers fields, to Django Rest Framework Documentation (soon) The full documentation is at https://django

Gilson Filho 19 Aug 30, 2022
Django-rest-auth provides a set of REST API endpoints for Authentication and Registration

This app makes it extremely easy to build Django powered SPA's (Single Page App) or Mobile apps exposing all registration and authentication related functionality as CBV's (Class Base View) and REST (JSON)

Tivix 2.4k Dec 29, 2022
Authentication for Django Rest Framework

Dj-Rest-Auth Drop-in API endpoints for handling authentication securely in Django Rest Framework. Works especially well with SPAs (e.g React, Vue, Ang

Michael 1.1k Dec 28, 2022
A JSON Web Token authentication plugin for the Django REST Framework.

Simple JWT Abstract Simple JWT is a JSON Web Token authentication plugin for the Django REST Framework. For full documentation, visit django-rest-fram

Jazzband 3.3k Jan 4, 2023
Introduction to Django Rest Framework

Introduction to Django Rest Framework This is the repository of the video series Introduction to Django Rest Framework published on YouTube. It is a s

Simple is Better Than Complex 20 Jul 14, 2022
JSON:API support for Django REST framework

JSON:API and Django REST framework Overview JSON:API support for Django REST framework Documentation: https://django-rest-framework-json-api.readthedo

null 1k Dec 27, 2022
DRF-extensions is a collection of custom extensions for Django REST Framework

Django REST Framework extensions DRF-extensions is a collection of custom extensions for Django REST Framework Full documentation for project is avail

Gennady Chibisov 1.3k Dec 28, 2022
Generate Views, Serializers, and Urls for your Django Rest Framework application

DRF Generators Writing APIs can be boring and repetitive work. Don't write another CRUDdy view in Django Rest Framework. With DRF Generators, one simp

Tobin Brown 332 Dec 17, 2022
Document Web APIs made with Django Rest Framework

DRF Docs Document Web APIs made with Django Rest Framework. View Demo Contributors Wanted: Do you like this project? Using it? Let's make it better! S

Manos Konstantinidis 626 Nov 20, 2022
Recursive Serialization for Django REST framework

djangorestframework-recursive Overview Recursive Serialization for Django REST framework This package provides a RecursiveField that enables you to se

null 336 Dec 28, 2022
Dropdown population implementation for Django REST Framework

drf-dropdown Dropdown population implementation for Django REST Framework Usage Add DropdownView to API URL # urls.py import dropdown urlpatterns = [

Preeti Yuankrathok 4 Dec 6, 2022
simple api build with django rest framework

Django Rest API django-rest-framework Employees management simple API in this project wrote test suites for endpoints wrote simple doc string for clas

OMAR.A 1 Mar 31, 2022
Simple Crud Api With Django Rest Framework

SIMPLE CRUD API WITH DJANGO REST FRAMEWORK Django REST framework is a powerful and flexible toolkit for building Web APIs. Requirements Python 3.6 Dja

kibet hillary 1 May 3, 2022
BloodDonors: Built using Django REST Framework for the API backend and React for the frontend

BloodDonors By Daniel Yuan, Alex Tian, Aaron Pan, Jennifer Yuan As the pandemic raged, one of the side effects was an urgent shortage of blood donatio

Daniel Yuan 1 Oct 24, 2021
Built on Django Rest Framework, to provide with command execution on linux terminal

Built on Django Rest Framework, to provide with command execution on linux terminal

null 1 Oct 31, 2021
RESTler is the first stateful REST API fuzzing tool for automatically testing cloud services through their REST APIs and finding security and reliability bugs in these services.

RESTler is the first stateful REST API fuzzing tool for automatically testing cloud services through their REST APIs and finding security and reliability bugs in these services.

Microsoft 1.8k Jan 4, 2023
Mlflow-rest-client - Python client for MLflow REST API

Python Client for MLflow Python client for MLflow REST API. Features: Minimal de

MTS 35 Dec 23, 2022
Django Ninja is a web framework for building APIs with Django and Python 3.6+ type hints.

?? Fast, Async-ready, Openapi, type hints based framework for building APIs

Vitaliy Kucheryaviy 3.8k Jan 4, 2023