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
Collection of Summer 2022 tech internships!

Collection of Summer 2022 tech internships!

Pitt Computer Science Club (CSC) 15.6k Jan 03, 2023
A simple document management REST based API for collaboratively interacting with documents

documan_api A simple document management REST based API for collaboratively interacting with documents.

Shahid Yousuf 1 Jan 22, 2022
30 Days of google cloud leaderboard website

30 Days of Cloud Leaderboard This is a leaderboard for the students of Thapar, Patiala who are participating in the 2021 30 days of Google Cloud Platf

Developer Student Clubs TIET 13 Aug 25, 2022
Zero configuration Airflow plugin that let you manage your DAG files.

simple-dag-editor SimpleDagEditor is a zero configuration plugin for Apache Airflow. It provides a file managing interface that points to your dag_fol

30 Jul 20, 2022
Yet Another MkDocs Parser

yamp Motivation You want to document your project. You make an effort and write docstrings. You try Sphinx. You think it sucks and it's slow -- I did.

Max Halford 10 May 20, 2022
Create Python API documentation in Markdown format.

Pydoc-Markdown Pydoc-Markdown is a tool and library to create Python API documentation in Markdown format based on lib2to3, allowing it to parse your

Niklas Rosenstein 375 Jan 05, 2023
DocumentPy is a Python application that runs in a command-line interface environment, made for creating HTML documents.

DocumentPy DocumentPy is a Python application that runs in a command-line interface environment, made for creating HTML documents. Usage DocumentPy, a

Lotus 0 Jul 15, 2021
Pydantic model generator for easy conversion of JSON, OpenAPI, JSON Schema, and YAML data sources.

datamodel-code-generator This code generator creates pydantic model from an openapi file and others. Help See documentation for more details. Supporte

Koudai Aono 1.3k Dec 29, 2022
🌱 Complete API wrapper of Seedr.cc

Python API Wrapper of Seedr.cc Table of Contents Installation How I got the API endpoints? Start Guide Getting Token Logging with Username and Passwor

Hemanta Pokharel 43 Dec 26, 2022
Test utility for validating OpenAPI documentation

DRF OpenAPI Tester This is a test utility to validate DRF Test Responses against OpenAPI 2 and 3 schema. It has built-in support for: OpenAPI 2/3 yaml

snok 106 Jan 05, 2023
Grokking the Object Oriented Design Interview

Grokking the Object Oriented Design Interview

Tusamma Sal Sabil 2.6k Jan 08, 2023
A Json Schema Generator

JSON Schema Generator Author : Eru Michael About A Json Schema Generator. This is a generic program that: Reads a JSON file similar to what's present

1 Nov 10, 2021
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 07, 2023
Python Deep Dive Course - Accompanying Materials

Python Deep Dive Various Jupyter notebooks and Python sources associated with my Udemy Python 3 Deep Dive course series: Part 1: Mainly functional pro

Fred Baptiste 1.1k Dec 30, 2022
Highlight Translator can help you translate the words quickly and accurately.

Highlight Translator can help you translate the words quickly and accurately. By only highlighting, copying, or screenshoting the content you want to translate anywhere on your computer (ex. PDF, PPT

Coolshan 48 Dec 21, 2022
Python bindings to OpenSlide

OpenSlide Python OpenSlide Python is a Python interface to the OpenSlide library. OpenSlide is a C library that provides a simple interface for readin

OpenSlide 297 Dec 21, 2022
Compare two CSV files for differences. Colorize the differences and align the columns.

pretty-csv-diff Compare two CSV files for differences. Colorize the differences and align the columns. Command-Line Example Command-Line Usage usage:

Devon 6 Dec 29, 2022
Autolookup GUI Plugin for Plover

Word Tray for Plover Word Tray is a GUI plugin that automatically looks up efficient outlines for words that start with the current input, much like a

Kathy 3 Jun 08, 2022
Python 3 wrapper for the Vultr API v2.0

Vultr Python Python wrapper for the Vultr API. https://www.vultr.com https://www.vultr.com/api This is currently a WIP and not complete, but has some

CSSNR 6 Apr 28, 2022
step by step guide for beginners for getting started with open source

Step-by-Step Guide for beginners for getting started with Open-Source Here The Contribution Begins 💻 If you are a beginner then this repository is fo

Arpit Jain 66 Jan 03, 2023