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
Windows Task Manager with special features, written in Python.

Killer That damn Chrome ⬇ Download here · 👋 Join our discord Tired of trying to kill processes with the default Windows Task Manager? Selecting one b

Nathan Araújo 49 Jan 03, 2023
tgEasy | Easy for a Brighter Shine | Monkey Patcher Addon for Pyrogram

tgEasy | Easy for a Brighter Shine | Monkey Patcher Addon for Pyrogram

Jayant Hegde Kageri 35 Nov 12, 2022
An application for automation of the mining function in the game Alienworlds.IO

alienautomation A Python script made to automate the tidious job of mining on AlienWorlds This script: Automatically opens the browser Automatically l

anonieXdev 42 Dec 03, 2022
CuraMultiplyByGrid - Cura Плагин для размножения детали сеткой на весь стол автоматически без поворота

CuraMultiplyByGrid Cura Плагин для размножения детали сеткой на весь стол автоматически без поворота. Размножение в куре настолько ужасно реализовано,

3 Dec 02, 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
Sabe is a python framework written for easy web server setup.

Sabe is a python framework written for easy web server setup. Sabe, kolay web sunucusu kurulumu için yazılmış bir python çerçevesidir. Öğrenmesi kola

2 Jan 01, 2022
A Classroom Engagement Platform

Project Introduction This is project introduction Setup Setting up Postgres This is the most tricky part when setting up the application. You will nee

Santosh Kumar Patro 1 Nov 18, 2021
Tools for analyzing Java JVM gc log files

gc_log This package consists of two separate utilities useful for : gc_log_visualizer.py regionsize.py GC Log Visualizer This was updated to run under

Brad Schoening 0 Jan 04, 2022
an opensourced roblox group finder writen in python 100% free and virus-free

Roblox-Group-Finder an opensourced roblox group finder writen in python 100% free and virus-free note : if you don't want install python or just use w

mollomm1 1 Nov 11, 2021
A function decorator for enforcing function signatures

A function decorator for enforcing function signatures

Emmanuel I. Obi 0 Dec 08, 2021
A project to empower needy-students.

Happy Project 😊 A project to empower needy-students. Happy Project is a non-profit initiation founded by IT people from Jaffna, Sri Lanka. This is to

1 Mar 14, 2022
SECRET SANTA / KRIS KINGLE

SECRET SANTA / KRIS KINGLE Note: Before executing the script, make sure to turn

DEV_FINWIZ 10 Dec 06, 2022
Film-dosimetry - Film dosimetry for DUVS

film-dosimetry Film dosimetry for DUVS Hi David and Joe, here we go this is a te

Christine L Kuryla 3 Jan 20, 2022
Automated Content Feed Curator

Gathers posts from content feeds, filters, formats, delivers to you.

Alper S. Soylu 2 Jan 22, 2022
Developed a website to analyze and generate report of students based on the curriculum that represents student’s academic performance.

Developed a website to analyze and generate report of students based on the curriculum that represents student’s academic performance. We have developed the system such that, it will automatically pa

VIJETA CHAVHAN 3 Nov 08, 2022
New multi tool im making adding features currently

Emera Multi Tool New multi tool im making adding features currently Current List of Planned Features - Linkvertise Bypasser - Discord Auto Bump - Gith

Lamp 3 Dec 03, 2021
Modern API wrapper for Genshin Impact built on asyncio and pydantic.

genshin.py Modern API wrapper for Genshin Impact built on asyncio and pydantic.

sadru 212 Jan 06, 2023
Repository voor verhalen over de woningbouw-opgave in Nederland

Analyse plancapaciteit woningen In deze notebook zetten we cijfers op een rij om de woningbouwplannen van Nederlandse gemeenten in kaart te kunnen bre

Follow the Money 10 Jun 30, 2022
March-madness - March Madness results 1985-2021

march-madness Results for all 2,268 NCAA Division I Men's Basketball Tournament games since the modern format was introduced in 1985. Includes years,

Darik Harter 2 Feb 26, 2022
Collatz Sanısını Test Eden Ve Kanıtlayan Bir Python Programı

Collatz Sanısı Collatz Sanısını Test Eden Ve Kanıtlayan Bir Python Programı. Kullanım Terminalde: 1- git clone https://github.com/detherminal/Collatz-

Cemal Mert 2 May 07, 2022