Comprehensive OpenAPI schema generator for Django based on pydantic

Overview

🗡️ Djagger

Package Badge Pypi Badge

Automated OpenAPI documentation generator for Django. Djagger helps you generate a complete and comprehensive API documentation of your Django project by utilizing pydantic to create schema objects for your views.

Djagger is designed to be:

🧾 Comprehensive - ALL aspects of your API should be document-able straight from your views, to the full extent of the OpenAPi 3.0 specification.

👐 Unintrusive - Integrate easily with your existing Django project. Djagger can document vanilla Django views (function-based and class-based views), as well as any Django REST framework views. As long as you are using Django's default URL routing, you are good to go. You do not need to redesign your APIs for better documentation.

🍭 Easy - Djagger uses pure, unadulterated pydantic models to generate schemas. If you have used pydantic, there is no learning curve. If you have not heard of pydantic, it is a powerful data validation library that is pretty straightforward to pickup (like dataclasses). Check it out here. Either way, documenting your APIs will feel less like a chore.

Quick start

Install using pip

pip install djagger

Add 'djagger' to your INSTALLED_APPS setting like this

INSTALLED_APPS = [
    ...
    'djagger',
]

Include the djagger URLconf in your project urls.py like this if you want to use the built-in document views.

urlpatterns = [
    ...
    path('djagger/', include('djagger.urls')),
]
To see the generated documentation, use the route /djagger/api/docs. Djagger uses Redoc as the default client generator.

To get the generated JSON schema file, use the route /djagger/schema.json.

Note that the path djagger/ is required when setting this URLconf. Feel free to remove djagger.urls when you are more comfortable and decide to customize your own documentation views. The routes provided here are for you to get started quickly.

Examples

In the examples, we alias pydantic BaseModel as Schema to avoid any confusion with Django's Model ORM objects. Django REST Framework views are used for the examples.

Example GET Endpoint

from rest_framework.views import APIView
from rest_framework.response import Response

from pydantic import BaseModel as Schema

class UserDetailsParams(Schema):

    pk : int

class UserDetailsResponse(Schema):
    """ GET response schema for user details
    """
    first_name : str
    last_name : str
    age : int
    email: str

class UserDetailsAPI(APIView):

    """ Lists a given user's details.
    Docstrings here will be used for the API's description in
    the generated schema.
    """

    get_path_params = UserDetailsParams
    get_response_schema = UserDetailsResponse

    def get(self, request, pk : int):

        return Response({
            "first_name":"John",
            "last_name":"Doe",
            "age": 30,
            "email":"[email protected]"
        })

Generated documentation

UserDetailsAPI Redoc

Example POST Endpoint

from pydantic import BaseModel as Schema, Field
from typing import Optional
from decimal import Decimal

class CreateItemRequest(Schema):
    """ POST request body schema for creating an item.
    """
    sku : str = Field(description="Unique identifier for an item")
    name : str = Field(description="Name of an item")
    price : Decimal = Field(description="Price of item in USD")
    min_qty : int = 1
    description : Optional[str]

class CreateItemResponse(Schema):
    """ Post response schema for successful item creation.
    """
    pk : int
    details : str = Field(description="Details for the user")

class CreateItemAPI(APIView):

    """ Endpoint to create an item.
    """

    summary = "Create Item API Title" # Change title of API
    post_body_params = CreateItemRequest
    post_response_schema = CreateItemResponse

    def post(self, request):

        # Some code here...

        return Response({
            "pk":1,
            "details":"Successfully created item."
        })

Generated documentation

CreateItemAPI Redoc

To include multiple responses for the above endpoint, for example, an error response code, create a new Schema for the error response and change the post_response_schema attribute to the following

class ErrorResponse(Schema):
    """ Response schema for errors.
    """
    status_code : int
    details : str = Field(description="Error details for the user")

class CreateItemAPI(APIView):

    """ API View to create an item.
    """

    summary = "Create Item API Title" # Change title of API
    post_body_params = CreateItemRequest
    post_response_schema = {
        "200": CreateItemResponse,
        "400": ErrorResponse
    }

    def post(self, request):
        ...

Generated documentation

ErrorResponse Redoc

Documentation & Support

  • Full documentation is currently a work in progress.
  • This project is in continuous development. If you have any questions or would like to contribute, please email [email protected]
  • If you want to support this project, do give it a on github!
Comments
  • Compatibility issue with DRF 3.14.0

    Compatibility issue with DRF 3.14.0

    NullBooleanField was removed starting from DRF 3.14.0

    So, I encounter this issue with current djagger version:

    Traceback (most recent call last):
      File "/home/tonio/.virtualenvs/backend-VcZ5AJ-y/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
        response = get_response(request)
      File "/home/tonio/.virtualenvs/backend-VcZ5AJ-y/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response
        response = wrapped_callback(request, *callback_args, **callback_kwargs)
      File "/home/tonio/.virtualenvs/backend-VcZ5AJ-y/lib/python3.7/site-packages/sentry_sdk/integrations/django/views.py", line 67, in sentry_wrapped_callback
        return callback(request, *args, **kwargs)
      File "/home/tonio/projets/pro/SubstancesActives/djagger/djagger/views.py", line 17, in open_api_json
        document = Document.generate(**doc_settings)
      File "/home/tonio/projets/pro/SubstancesActives/djagger/djagger/openapi.py", line 956, in generate
        path = Path.create(view)
      File "/home/tonio/projets/pro/SubstancesActives/djagger/djagger/openapi.py", line 826, in create
        operation = Operation._from(view_func, http_method)
      File "/home/tonio/projets/pro/SubstancesActives/djagger/djagger/openapi.py", line 768, in _from
        operation._extract_responses(view, http_method)
      File "/home/tonio/projets/pro/SubstancesActives/djagger/djagger/openapi.py", line 639, in _extract_responses
        responses = {"200": Response._from(response_schema)}
      File "/home/tonio/projets/pro/SubstancesActives/djagger/djagger/openapi.py", line 399, in _from
        content={content_type: MediaType._from(model)},
      File "/home/tonio/projets/pro/SubstancesActives/djagger/djagger/openapi.py", line 267, in _from
        model = SerializerConverter(s=model).to_model()
      File "/home/tonio/projets/pro/SubstancesActives/djagger/djagger/serializers.py", line 252, in to_model
        return self.from_serializer(self.s())
      File "/home/tonio/projets/pro/SubstancesActives/djagger/djagger/serializers.py", line 218, in from_serializer
        t = cls.infer_field_type(field, field_name)
      File "/home/tonio/projets/pro/SubstancesActives/djagger/djagger/serializers.py", line 98, in infer_field_type
        fields.NullBooleanField: bool,
    AttributeError: module 'rest_framework.fields' has no attribute 'NullBooleanField'
    
    opened by tonioo 4
  • feat: added DJAGGER_DOCUMENT url_names parameter to resolve url also with their names

    feat: added DJAGGER_DOCUMENT url_names parameter to resolve url also with their names

    with this feature we extend the DJAGGER_DOCUMENT paramenters and we can configure the resouces also with url_names. Eg:

    DJAGGER_DOCUMENT = {
        "app_names" : ['my_entire_app'],
        "url_names": ['oidc_provider_token_endpoint']
    }
    
    enhancement 
    opened by peppelinux 4
  • Fixed duplicate content issue when we have more than 1 ListAPIView.

    Fixed duplicate content issue when we have more than 1 ListAPIView.

    To reproduce the issue, just create a project with two generic API views (inheriting from ListAPIView in my case) and do not override the get() method. Put custom description and response schema using the get_summary and response_schema shortcuts. You end up with a documentation containing two routes (expected) but with the same content!

    This is due to the fact that in the Document class, you end up playing with the get() method of the base class (ListAPIView), which remains the same instance whatever the route... With the if statement that was present, only the first view wins.

    I guess this error might happen in other cases but I only tested the one described above.

    opened by tonioo 2
  • 1.1.3

    1.1.3

    Fixed

    • Fixed bug where authorizations and security schemes were not being rendered. components parameter passed was not being proceessed in Document.generate.
    bug 
    opened by royhzq 0
  • 1.1.2

    1.1.2

    Prep for 1.1.2 release

    Added

    • Added missing .gitignore file.

    Changed

    • Updated changelog and sphinx docs.

    Fixed

    • Fixed date typos in this changelog file.
    opened by royhzq 0
  • 1.1.1

    1.1.1

    [1.1.1] - 2021-04-06

    Added

    • Rest framework serializers.ChoiceField and serializers.MultipleChoiceField will now be represented as Enum types with enum values correctly reflected in the schema.
    • Documentation for using Tags.

    Fixed

    • Fix bug where schema examples are not generated correctly.
    • Fix bug where the request URL for the objects are generated with an incorrect prefix.
    opened by royhzq 0
  • Serializer to pydantic model conversion for ChoiceField and MultipleChoiceField

    Serializer to pydantic model conversion for ChoiceField and MultipleChoiceField

    ChoiceField and MultipleChoiceField in serializers are represented as string after being converted to a pydantic model. Consider representing as Enum field type.

    opened by royhzq 0
Releases(1.1.4)
  • 1.1.4(Oct 31, 2022)

    [1.1.4] - 2022-10-31

    Removed

    • Removed support for DRF NullBooleanField field for compatibility with the latest DRF version 3.14.
    • Removed mapping of DRF serializer label to pydantic Field alias parameter.

    Fixed

    • Bug where documentation for generic views are duplicated.
    Source code(tar.gz)
    Source code(zip)
  • 1.1.3(Apr 19, 2022)

    [1.1.3] - 2022-04-17

    Fixed

    • Fixed bug where authorizations and security schemes were not being rendered. components parameter passed was not being proceessed in Document.generate.
    Source code(tar.gz)
    Source code(zip)
  • 1.1.2(Apr 6, 2022)

    [1.1.2] - 2022-04-06

    Added

    • Added url_names parameter to get_url_patterns to allow DJAGGER_DOCUMENT to filter API endpoints that should be documented via their url names.
    • Added missing .gitignore file.

    Fixed

    • Fixed date typos in this changelog file.
    Source code(tar.gz)
    Source code(zip)
  • 1.1.1(Jan 6, 2022)

    [1.1.1] - 2021-04-06

    Added

    • Rest framework serializers.ChoiceField and serializers.MultipleChoiceField will now be represented as Enum types with enum values correctly reflected in the schema.
    • Documentation for using Tags.

    Fixed

    • Fix bug where schema examples are not generated correctly.
    • Fix bug where the request URL for the objects are generated with an incorrect prefix.
    Source code(tar.gz)
    Source code(zip)
  • 1.1.0(Jan 4, 2022)

    1.1.0

    Added

    • Added documentation.
    • Support for generic views and viewsets.
    • Support for DRF Serializer to pydantic model conversion.
    • Support for multiple responses and different response content types.
    • Support for function-based views via schema decorator.
    • Added option for a global prefix to all Djagger attributes.
    • Generated schema fully compatible with OpenAPI 3.

    Removed

    • djagger.swagger.* pydantic models. Removed support for Swagger 2.0 specification.
    Source code(tar.gz)
    Source code(zip)
  • 1.0.0(Dec 11, 2021)

    This is the first Djagger release. New

    • Auto-generates complete OpenAPI schema for all API routes discovered in the Django project.
    • Supports schema generation for Django Class-based views and Function-based views.
    • Supports schema generation for all Django REST Framework API views (class-based and function-based).
    Source code(tar.gz)
    Source code(zip)
Owner
Roy's Repositories
An app that mirrors your phone to your compute and maps controller input to the screen

What is 'Dragalia Control'? An app that mirrors your phone to your compute and maps controller input to the screen. Inputs are mapped specifically for

1 May 03, 2022
Archive, organize, and watch for changes to publicly available information.

0. Overview The Trapper Keeper is a collection of scripts that support archiving information from around the web to make it easier to study and use. I

Bill Fitzgerald 9 Oct 26, 2022
Modify the value and status of the records KoboToolbox

Modify the value and status of the records KoboToolbox (Modica el valor y status de los registros de KoboToolbox)

1 Oct 30, 2021
Artificial intelligence based on 5-dimensional quantum selection

Deep Thought An artificial intelligence based on 5-dimensional quantum selection. Algorithm The payload Make an random bit array (e.g. 1101...) Conver

Larry Holst 3 Dec 14, 2022
A simple PID tuner and simulator.

PIDtuner-V0.1 PlantPy PID tuner version 0.1 Features Supports first order and ramp process models. Supports Proportional action on PV or error or a sp

3 Jun 23, 2022
用于导出墨墨背单词的词库,并生成适用于 List 背单词,不背单词,欧陆词典等的自定义词库

maimemo-export 用于导出墨墨背单词的词库,并生成适用于 List 背单词,欧陆词典,不背单词等的自定义词库。 仓库内已经导出墨墨背单词所有自带词库(暂不包括云词库),多达 900 种词库,可以在仓库中选择需要的词库下载(下载单个文件的方法),也可以去 蓝奏云(密码:666) 下载打包好

ourongxing 293 Dec 29, 2022
pythonOS: An operating system kernel made in python and assembly

pythonOS An operating system kernel made in python and assembly Wait what? It uses a custom compiler called snek that implements a part of python3.9 (

Abbix 69 Dec 23, 2022
Module for remote in-memory Python package/module loading through HTTP/S

httpimport Python's missing feature! The feature has been suggested in Python Mailing List Remote, in-memory Python package/module importing through H

John Torakis 220 Dec 17, 2022
A joke conlang with minimal semantics

SyntaxLang Reserved Defined Words Word Function fo Terminates a noun phrase or verb phrase tu Converts an adjective block or sentence to a noun to Ter

Leo Treloar 1 Dec 07, 2021
Auto check in via GitHub Actions

因为本人毕业离校,本项目交由在校的@hfut-xyc同学接手,请访问hfut-xyc/hfut_auto_check-in获得最新的脚本 本项目遵从GPLv2协定,Copyright (C) 2021, Fw[a]rd 免责声明 根据GPL协定,我、本项目的作者,不会对您使用这个脚本带来的任何后果

Fw[a]rd 3 Jun 27, 2021
Extrator de dados do jupiterweb

Extrator de dados do jupiterweb O programa é composto de dois arquivos: Um constando apenas de classes complementares que representam as unidades e as

Bruno Aricó 2 Nov 28, 2022
Scientific Programming: A Crash Course

Scientific Programming: A Crash Course Welcome to the Scientific Programming course. My name is Jon Carr and I am a postdoc in Davide Crepaldi's lab.

Jon Carr 1 Feb 17, 2022
The git for the Python Story Utility Package library.

PSUP, The Python Story Utility Package Module. PSUP helps making stories or games with options, diverging paths, different endings and so on. You can

Enoki 6 Nov 27, 2022
A simple chatbot that I made for school project

Chatbot: Python A simple chatbot that I made for school Project. Tho this chatbot is dumb sometimes, but it's not too bad lol. Check it Out! FAQ How t

Prashant 2 Nov 13, 2021
Compiler Final Project - Lisp Interpreter

Compiler Final Project - Lisp Interpreter

2 Jan 23, 2022
Grail(TM) is a web browser written in Python

Grail is distributed in source form. It requires that you have a Python interpreter and a Tcl/Tk installation, with the Python interpreter configured for Tcl/Tk support.

22 Oct 18, 2022
Simple Python tool to check if there is an Office 365 instance linked to a domain.

o365chk.py Simple Python script to check if there is an Office365 instance linked to a particular domain.

Steven Harris 37 Jan 02, 2023
A Python script to convert your favorite TV series into an Anki deck.

Ankiniser A Python3.8 script to convert your favorite TV series into an Anki deck. How to install? Download the script with git or download it manualy

37 Nov 03, 2022
Mpis-ex7 - Implementation of tasks 1, 2, 3 for Metody Probabilistyczne i Statystyka Lista 7

Implementations of task 1, 2 and 3 from here Author: Maciej Bazela Index: 261743 Each task was implemented in Python 3. I've used Cython to speed up e

Maciej Bazela 1 Feb 27, 2022
dotfiles - Cristian Valero Abundio

In this repository you can find various configurations to configure your Linux operating system, preferably ArchLinux and its derivatives.

Cristian Valero Abundio 1 Jan 09, 2022