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
null
Feature engineering library that helps you keep track of feature dependencies, documentation and schema

Feature engineering library that helps you keep track of feature dependencies, documentation and schema

null 28 May 31, 2022
A curated list of awesome things related to Pydantic! 🌪️

Awesome Pydantic A curated list of awesome things related to Pydantic. These packages have not been vetted or approved by the pydantic team. Feel free

Marcelo Trylesinski 186 Jan 5, 2023
🪄 Auto-generate Streamlit UI from Pydantic Models and Dataclasses.

Streamlit Pydantic Auto-generate Streamlit UI elements from Pydantic models. Getting Started • Documentation • Support • Report a Bug • Contribution •

Lukas Masuch 103 Dec 25, 2022
Tie together `drf-spectacular` and `djangorestframework-dataclasses` for easy-to-use apis and openapi schemas.

Speccify Tie together drf-spectacular and djangorestframework-dataclasses for easy-to-use apis and openapi schemas. Usage @dataclass class MyQ

Lyst 4 Sep 26, 2022
Comprehensive Python Cheatsheet

Comprehensive Python Cheatsheet

Jure Šorn 31.3k Dec 30, 2022
Package pyVHR is a comprehensive framework for studying methods of pulse rate estimation relying on remote photoplethysmography (rPPG)

Package pyVHR (short for Python framework for Virtual Heart Rate) is a comprehensive framework for studying methods of pulse rate estimation relying on remote photoplethysmography (rPPG)

PHUSE Lab 261 Jan 3, 2023
FollowSpot is a comprehensive audition tracking fullstack web application for entertainment industry professionals.

FollowSpot is a comprehensive audition tracking fullstack web application for entertainment industry professionals. This app allows users to store information/media for all of their auditions while also compiling data and displaying statistics to help track progress.

Jen Brissman 9 Jul 12, 2022
Senior Comprehensive Project For Python

Senior Comprehensive Project Author: Grey Hutchinson My project, which I nicknamed “Murmur”, was to create a research tool that would use neural netwo

null 1 May 29, 2022
Random Turkish name generator with realistic probabilities.

trnames Random Turkish name generator with realistic probabilities. Based on Trey Hunner's names package. Installation The package can be installed us

Kaan Öztürk 20 Jan 2, 2023
An advanced pencil sketch generator

Pencilate An advanced pencil sketch generator About : An advanced pencil sketch maker made in just 12 lines of code. Yes you read it right, JUST 12 LI

MAINAK CHAUDHURI 23 Dec 17, 2022
TrackGen - The simplest tropical cyclone track map generator

TrackGen - The simplest tropical cyclone track map generator Usage Each line is a point to be plotted on the map Each field gives information about th

TrackGen 6 Jul 20, 2022
A beacon generator using Cobalt Strike and a variety of tools.

Beaconator is an aggressor script for Cobalt Strike used to generate either staged or stageless shellcode and packing the generated shellcode using your tool of choice.

Capt. Meelo 441 Dec 17, 2022
Anki cards generator for Leetcode

Leetcode Anki card generator Summary By running this script you'll be able to generate Anki cards with all the leetcode problems. I personally use it

Pavel Safronov 150 Dec 25, 2022
NFT generator for Solana!

Solseum NFT Generator for Solana! Check this guide here! Creating your randomized uniques NFTs, getting rarity information and displaying it on a webp

Solseum™ VR NFTs 145 Dec 30, 2022
Tucan Discord Token Generator - Remastered

TucanGEN-SRC Tucan Discord Token Generator - Remastered Tucan source made better by me. -- idk if it works anymore Includes: hCaptcha Bypass Automatic

Vast 8 Nov 4, 2022
A module comment generator for python

Module Comment Generator The comment style is as a tribute to the comment from the RA . The comment generator can parse the ast tree from the python s

飘尘 1 Oct 21, 2021
Python Excuse Generator

Excuse Generator Python Excuse Generator This project is an excuse generator that provides the user with an excuse as to why they weren't paying atten

Collin Sanders 5 Jul 7, 2022
A simple single-color identicon generator

Identicons What are identicons? Setup: git clone https://github.com/vjdad4m/identicons.git cd identicons pip3 install -r requirements.txt chmod +x

Adam Vajda 1 Oct 31, 2021
A feed generator. Currently supports generating RSS feeds from Google, Bing, and Yahoo news.

A feed generator. Currently supports generating RSS feeds from Google, Bing, and Yahoo news.

Josh Cardenzana 0 Dec 13, 2021