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
Sms Bomber, Tool Encryptor

ɴᴏʙɪᴛᴀシ︎ ғᴏʀ ᴀɴʏ ʜᴇʟᴘシ︎ Install pkg install git -y pkg install python -y pip install requests git clone https://github.com/AK27HVAU/akash Run cd Akash

ɴᴏʙɪᴛᴀシ︎ 4 May 23, 2022
Cleaner script to normalize knock's output EPUBs

clean-epub The excellent knock application by Benton Edmondson outputs EPUBs that seem to be DRM-free. However, if you run the application twice on th

2 Dec 16, 2022
This repository outlines deploying a local Kubeflow v1.3 instance on microk8s and deploying a simple MNIST classifier using KFServing.

Zero to Inference with Kubeflow Getting Started This repository houses all of the tools, utilities, and example pipeline implementations for exploring

Ed Henry 3 May 18, 2022
Modified fork of CPython's ast module that parses `# type:` comments

Typed AST typed_ast is a Python 3 package that provides a Python 2.7 and Python 3 parser similar to the standard ast library. Unlike ast up to Python

Python 217 Dec 06, 2022
Beautiful static documentation generator for OpenAPI/Swagger 2.0

Spectacle The gentleman at REST Spectacle generates beautiful static HTML5 documentation from OpenAPI/Swagger 2.0 API specifications. The goal of Spec

Sourcey 1.3k Dec 13, 2022
An awesome Data Science repository to learn and apply for real world problems.

AWESOME DATA SCIENCE An open source Data Science repository to learn and apply towards solving real world problems. This is a shortcut path to start s

Academic.io 20.3k Jan 09, 2023
Generate a single PDF file from MkDocs repository.

PDF Generate Plugin for MkDocs This plugin will generate a single PDF file from your MkDocs repository. This plugin is inspired by MkDocs PDF Export P

198 Jan 03, 2023
An introduction course for Python provided by VetsInTech

Introduction to Python This is an introduction course for Python provided by VetsInTech. For every "boot camp", there usually is a pre-req, but becaus

Vets In Tech 2 Dec 02, 2021
Manage your WordPress installation directly from SublimeText SideBar and Command Palette.

WordpressPluginManager Manage your WordPress installation directly from SublimeText SideBar and Command Palette. Installation Dependencies You will ne

Art-i desenvolvimento 1 Dec 14, 2021
Automatic links from code examples to reference documentation

sphinx-codeautolink Automatic links from Python code examples to reference documentation at the flick of a switch! sphinx-codeautolink analyses the co

Felix Hildén 41 Dec 17, 2022
MonsterManualPlus - An advanced monster manual for Tower of the Sorcerer.

Monster Manual + This is an advanced monster manual for Tower of the Sorcerer mods. Users can get a plenty of extra imformation for decision making wh

Yifan Zhou 1 Jan 01, 2022
JTEX is a command line tool (CLI) for rendering LaTeX documents from jinja-style templates.

JTEX JTEX is a command line tool (CLI) for rendering LaTeX documents from jinja-style templates. This package uses Jinja2 as the template engine with

Curvenote 15 Dec 21, 2022
The OpenAPI Specification Repository

The OpenAPI Specification The OpenAPI Specification is a community-driven open specification within the OpenAPI Initiative, a Linux Foundation Collabo

OpenAPI Initiative 25.5k Dec 29, 2022
Explorative Data Analysis Guidelines

Explorative Data Analysis Get data into a usable format! Find out if the following predictive modeling phase will be successful! Combine everything in

Florian Rohrer 18 Dec 26, 2022
Documentation for GitHub Copilot

NOTE: GitHub Copilot discussions have moved to the Copilot Feedback forum. GitHub Copilot Welcome to the GitHub Copilot user community! In this reposi

GitHub 21.3k Dec 28, 2022
A powerful Sphinx changelog-generating extension.

What is Releases? Releases is a Python (2.7, 3.4+) compatible Sphinx (1.8+) extension designed to help you keep a source control friendly, merge frien

Jeff Forcier 166 Dec 29, 2022
Portfolio project for Code Institute Full Stack software development course.

Comic Sales tracker This project is the third milestone project for the Code Institute Diploma in Full Stack Software Development. You can see the fin

1 Jan 10, 2022
Contains the assignments from the course Building a Modern Computer from First Principles: From Nand to Tetris.

Contains the assignments from the course Building a Modern Computer from First Principles: From Nand to Tetris.

Matheus Rodrigues 1 Jan 20, 2022
🏆 A ranked list of awesome python developer tools and libraries. Updated weekly.

Best-of Python Developer Tools 🏆 A ranked list of awesome python developer tools and libraries. Updated weekly. This curated list contains 250 awesom

Machine Learning Tooling 646 Jan 07, 2023
Feature Store for Machine Learning

Overview Feast is an open source feature store for machine learning. Feast is the fastest path to productionizing analytic data for model training and

Feast 3.8k Dec 30, 2022