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
One line Brainfuck interpreter in Python

One line Brainfuck interpreter in Python

16 Dec 21, 2022
dragmap-meth: Fast and accurate aligner for bisulfite sequencing reads using dragmap

dragmap_meth (dragmap_meth.py) Alignment of BS-Seq reads using dragmap. Intro This works for single-end reads and for paired-end reads from the direct

Shaojun Xie 3 Jul 14, 2022
Box CRUD API With Python

Box CRUD API: Consider a store which has an inventory of boxes which are all cuboid(which have length breadth and height). Each Cuboid has been added

Akhil Bhalerao 3 Feb 17, 2022
Contains a Jupyter Notebook for calculating remaining plants required based on field/lathhouse data.

Davis-Sunflowers-Su21 Project goals: Plants influence their reproduction and mating system in many ways. Various factors such as time of flowering, ab

1 Feb 10, 2022
NFT-Image-Generator - Utility to generate a large collection of unique images

NFT-Image-Generator Utility for creating a generative art collection from suppli

Sem Moolenschot 60 Dec 15, 2022
Webcash is an experimental e-cash (electronic cash)

Webcash Webcash is an experimental new electronic cash ("e-cash") that enables decentralized and instant payments to anyone, anywhere in the world. Us

Mark Friedenbach 0 Feb 26, 2022
Checks for Vaccine Availability at your district and notifies you using E-mail, subscribe to our website.

Vaccine Availability Notifier Project Description Checks for Vaccine Availability at your district and notifies you using E-mail every 10 mins. Kindly

Farhan Hai Khan 19 Jun 03, 2021
HairCLIP: Design Your Hair by Text and Reference Image

Overview This repository hosts the official PyTorch implementation of the paper: "HairCLIP: Design Your Hair by Text and Reference Image". Our single

322 Dec 30, 2022
Fofa asset consolidation script

资产收集+C段整理二合一 基于fofa资产搜索引擎进行资产收集,快速检索目标条件下的IP,URL以及标题,适用于资产较多时对模糊资产的快速检索,新增C段整理功能,整理出

白泽Sec安全实验室 36 Dec 01, 2022
Telegram bot to remove the forwarded tag from messages.

Anonymous Sender Bot @AnonySendBot Telegram bot to remove the forwarded tag from messages. Table of Contents Usage Deploy To Heroku Local Deploying En

Stark Bots 26 Nov 24, 2022
清晰易读的7x7像素点阵中文字体和取模工具

FontChinese7x7 上古神器 III : 7x7像素点阵中文字体 想要在低分辨率屏幕上显示中文, 却发现中文字体实在是太大? 找了全网发现字体库最小也只有12x12? 甚至是好不容易找到了一个8x8字体, 结果发现字体收费且明确说明不得以任何形式嵌入到软件当中? 那就让这个项目来解决你的问

Angelic47 72 Dec 12, 2022
Learn Python Regular Expressions step by step from beginner to advanced levels

Python re(gex)? Learn Python Regular Expressions step by step from beginner to advanced levels with hundreds of examples and exercises The book also i

Sundeep Agarwal 1.3k Dec 28, 2022
Sequence clustering and database creation using mmseqs, from local fasta files

Sequence clustering and database creation using mmseqs, from local fasta files

Ana Julia Velez Rueda 3 Oct 27, 2022
Service for working with open data of the State Duma of the Russian Federation

Сервис для работы с открытыми данными Госдумы РФ Исходные данные из API Госдумы РФ извлекаются с помощью Apache Nifi и приземляются в хранилище Clickh

Aleksandr Sergeenko 2 Feb 14, 2022
Translation patch for Hololive ERROR

Translation patch for Hololive ERROR How do I install the patch? Grab the Translation.zip file for the latest version from the releases page, and unzi

18 Jul 20, 2022
Assembly example for CadQuery

Spindle and vacuum attachment This is a model of the vacuum attachment for my Workbee CNC router. There is a mist spray coming from the left hand side

Marcus Boyd 20 Sep 16, 2022
Python - Aprendendo Python na ByLearn

PYTHON Identação Escopo Pai Escopo filho Escopo neto Variaveis

Italo Rafael 3 May 31, 2022
Developing a python based app prototype with KivyMD framework for a competition :))

Developing a python based app prototype with KivyMD framework for a competition :))

Jay Desale 1 Jan 10, 2022
Dungeon Dice Rolls is an aplication that the user can roll dices (d4, d6, d8, d10, d12, d20 and d100) and store the results in one of the 6 arrays.

Dungeon Dice Rolls is an aplication that the user can roll dices (d4, d6, d8, d10, d12, d20 and d100) and store the results in one of the 6 arrays.

Bracero 1 Dec 31, 2021
Calculatrix is a project where I'll create plenty of calculators in a lot of differents languages

Calculatrix What is Calculatrix ? Calculatrix is a project where I'll create plenty of calculators in a lot of differents languages. I know this sound

1 Jun 14, 2022