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
Here is my Senior Design Project that I implemented to graduate from Computer Engineering.

Here is my Senior Design Project that I implemented to graduate from Computer Engineering. It is a chatbot made in RASA and helps the user to plan their vacation in the Turkish language. In order to

Ezgi Subaşı 25 May 31, 2022
This repository contains code for building education startup.

Learning Management System Overview It's the code for EssayBrain, a tool for teacher that automatically grades and validates essays. In order to valid

Shyam Das Shrestha 1 Nov 21, 2021
Application launcher and environment management

Application launcher and environment management for 21st century games and digital post-production, built with bleeding-rez and Qt.py News Date Releas

10 Nov 03, 2022
A "multiclipboards" script for an efficient way to improve the original clipboards which are only able to save one string at a time

A "multiclipboards" script for an efficient way to improve the original clipboards which are only able to save one string at a time. Works on both Windows and Linux.

1 Jan 24, 2022
Trackthis - This library can be used to track USPS and UPS shipments.

Trackthis - This library can be used to track USPS and UPS shipments. It has the option of returning the raw API response, or optionally, it can be used to standardize the USPS and UPS responses so t

Aaron Guzman 0 Mar 29, 2022
Make pack up python files easier.

python-easy-pack make pack up python files easier. 目前只提供了中文环境 如何使用? 将index.py复制到你的项目文件夹,或者把.py文件拷贝到这个文件夹。 打开你的cmd或者powershell 切换到程序所在目录,输入python index

2 Dec 15, 2021
Ergonomic option parser on top of dataclasses, inspired by structopt.

oppapī Ergonomic option parser on top of dataclasses, inspired by structopt. Usage from typing import Optional from oppapi import from_args, oppapi @

yukinarit 4 Jul 19, 2022
BlackMamba is a multi client C2/post exploitation framework

BlackMamba is a multi client C2/post exploitation framework with some spyware features. Powered by Python 3.8.6 and QT Framework.

Gustavo 873 Dec 29, 2022
Curso de Python 3 do Básico ao Avançado

Curso de Python 3 do Básico ao Avançado Desafio: Buscador de arquivos Criar um programa que faça a pesquisa de arquivos. É fornecido o caminho e um te

Diego Guedes 1 Jan 21, 2022
Replite - An embeddable REPL powered by JupyterLite

replite An embeddable REPL, powered by JupyterLite. Usage To embed the code cons

Jeremy Tuloup 47 Nov 09, 2022
An easy-to-learn, dynamic, interpreted, procedural programming language

Gen Programming Language WARNING!! THIS LANGUAGE IS IN DEVELOPMENT. ANYTHING CAN CHANGE AT ANY MOMENT. Gen is a dynamic, interpreted, procedural progr

Gen Programming Language 7 Oct 17, 2022
Convert a .vcf file to 'aa_table.tsv', including depth & alt frequency info

Produce an 'amino acid table' file from a vcf, including depth and alt frequency info.

Dan Fornika 1 Oct 16, 2021
Validate UC alumni identifier numbers with Python 3.

UC number validator Validate UC alumni identifier numbers with Python 3. Getting started Install the library with: pip install -U ucnumber Usage from

Open Source eUC 1 Jul 07, 2021
A variant caller for the GBA gene using WGS data

Gauchian: WGS-based GBA variant caller Gauchian is a targeted variant caller for the GBA gene based on a whole-genome sequencing (WGS) BAM file. Gauch

Illumina 16 Oct 13, 2022
dynamically create __slots__ objects with less code

slots_factory Factory functions and decorators for creating slot objects Slots are a python construct that allows users to create an object that doesn

Michael Green 2 Sep 07, 2021
Basit bir cc generator'ü.

Basit bir cc generator'ü. Setup What To Do; Python Installation We install python from CLICK Generator Board After installing the file and python, we

Lâving 7 Jan 09, 2022
Find virtual hosts (vhosts) from IP addresses and hostnames

Features Enumerate vhosts from a list of IP addresses and domain names. Virtual Hosts are enumerated using the following process: Supplied domains are

3 Jul 09, 2022
Cisco IOS-XE Operations Program. Shows operational data using restconf and yang

XE-Ops View operational and config data from devices running Cisco IOS-XE software. NoteS The build folder is the latest build. All other files are fo

18 Jul 23, 2022
Simple yet flexible natural sorting in Python.

natsort Simple yet flexible natural sorting in Python. Source Code: https://github.com/SethMMorton/natsort Downloads: https://pypi.org/project/natsort

Seth Morton 712 Dec 23, 2022
Write a program that works out whether if a given year is a leap year

Leap Year 💪 This is a Difficult Challenge 💪 Instructions Write a program that works out whether if a given year is a leap year. A normal year has 36

Rodrigo Santos 0 Jun 22, 2022