All Projects → axnsan12 → Drf Yasg

axnsan12 / Drf Yasg

Licence: other
Automated generation of real Swagger/OpenAPI 2.0 schemas from Django REST Framework code.

Programming Languages

python
139335 projects - #7 most used programming language
javascript
184084 projects - #8 most used programming language
HTML
75241 projects

Projects that are alternatives of or similar to Drf Yasg

Swagger Ui
Swagger UI is a collection of HTML, JavaScript, and CSS assets that dynamically generate beautiful documentation from a Swagger-compliant API.
Stars: ✭ 21,279 (+743.4%)
Mutual labels:  rest-api, rest, swagger, openapi, swagger-ui, openapi-specification
Swagger Codegen
swagger-codegen contains a template-driven engine to generate documentation, API clients and server stubs in different languages by parsing your OpenAPI / Swagger definition.
Stars: ✭ 13,859 (+449.31%)
Mutual labels:  rest-api, rest, swagger, openapi-specification, swagger-codegen
Django Ninja
💨 Fast, Async-ready, Openapi, type hints based framework for building APIs
Stars: ✭ 875 (-65.32%)
Mutual labels:  rest-api, swagger, openapi, swagger-ui, django
Swagger Core
Examples and server integrations for generating the Swagger API Specification, which enables easy access to your REST API
Stars: ✭ 6,898 (+173.4%)
Mutual labels:  rest-api, rest, swagger, openapi, openapi-specification
Swagger Parser
Swagger Spec to Java POJOs
Stars: ✭ 468 (-81.45%)
Mutual labels:  rest-api, rest, swagger, openapi, openapi-specification
Flasgger
Easy OpenAPI specs and Swagger UI for your Flask API
Stars: ✭ 2,825 (+11.97%)
Mutual labels:  rest-api, swagger, openapi, swagger-ui, openapi-specification
Springdoc Openapi
Library for OpenAPI 3 with spring-boot
Stars: ✭ 1,113 (-55.89%)
Mutual labels:  rest-api, swagger, openapi, swagger-ui, openapi-specification
Drf Spectacular
Sane and flexible OpenAPI 3 schema generation for Django REST framework.
Stars: ✭ 414 (-83.59%)
Mutual labels:  rest-api, swagger, openapi-specification, documentation-generator, django
Swagger Editor
Swagger Editor
Stars: ✭ 7,365 (+191.91%)
Mutual labels:  rest-api, rest, swagger, swagger-ui, openapi-specification
Redoc
📘 OpenAPI/Swagger-generated API Reference Documentation
Stars: ✭ 15,935 (+531.59%)
Mutual labels:  swagger, openapi, documentation-generator, openapi-specification, redoc
Fastapi
FastAPI framework, high performance, easy to learn, fast to code, ready for production
Stars: ✭ 39,588 (+1469.08%)
Mutual labels:  rest, swagger, openapi, swagger-ui, redoc
Swagger Inflector
Stars: ✭ 131 (-94.81%)
Mutual labels:  rest-api, rest, swagger, openapi-specification
Apispec
A pluggable API specification generator. Currently supports the OpenAPI Specification (f.k.a. the Swagger specification)..
Stars: ✭ 831 (-67.06%)
Mutual labels:  rest-api, swagger, openapi, openapi-specification
Swagger Node
Swagger module for node.js
Stars: ✭ 3,917 (+55.25%)
Mutual labels:  rest-api, rest, swagger, openapi-specification
Proteus
Lean, mean, and incredibly fast JVM framework for web and microservice development.
Stars: ✭ 178 (-92.94%)
Mutual labels:  rest-api, rest, swagger, openapi
Gemini
Model Driven REST framework to automatically generate CRUD APIs
Stars: ✭ 138 (-94.53%)
Mutual labels:  rest-api, rest, swagger, openapi
Best Of Web Python
🏆 A ranked list of awesome python libraries for web development. Updated weekly.
Stars: ✭ 1,118 (-55.69%)
Mutual labels:  rest-api, openapi, django, django-rest-framework
The Complete Guide To Drf And Vuejs
📢 Source Code from my Web Dev Course *The Complete Guide To Django REST Framework and Vue JS* (Lang: English & Italian)
Stars: ✭ 78 (-96.91%)
Mutual labels:  rest-api, rest, django, django-rest-framework
Mockoon
Mockoon is the easiest and quickest way to run mock APIs locally. No remote deployment, no account required, open source.
Stars: ✭ 3,448 (+36.66%)
Mutual labels:  rest-api, rest, swagger, openapi
Django Rest Swagger Docs
Beginners approach to Django Rest Swagger
Stars: ✭ 86 (-96.59%)
Mutual labels:  swagger, swagger-ui, django, django-rest-framework

drf-yasg - Yet another Swagger generator

GitHub Workflow Status Codecov  ReadTheDocs  PyPI

Generate real Swagger/OpenAPI 2.0 specifications from a Django Rest Framework API.

Compatible with

  • Django Rest Framework: 3.10, 3.11, 3.12
  • Django: 2.2, 3.0, 3.1
  • Python: 3.6, 3.7, 3.8, 3.9

Only the latest patch version of each major.minor series of Python, Django and Django REST Framework is supported.

Only the latest version of drf-yasg is supported. Support of old versions is dropped immediately with the release of a new version. Please do not create issues before upgrading to the latest release available at the time. Regression reports are accepted and will be resolved with a new release as quickly as possible. Removed features will usually go through a deprecation cycle of a few minor releases.

Resources:

Heroku deploy button

OpenAPI 3.0 note

If you are looking to add Swagger/OpenAPI support to a new project you might want to take a look at drf-spectacular, which is an actively maintained new library that shares most of the goals of this project, while working with OpenAPI 3.0 schemas.

OpenAPI 3.0 provides a lot more flexibility than 2.0 in the types of API that can be described. drf-yasg is unlikely to soon, if ever, get support for OpenAPI 3.0.

Features

  • full support for nested Serializers and Schemas
  • response schemas and descriptions
  • model definitions compatible with codegen tools
  • customization hooks at all points in the spec generation process
  • JSON and YAML format for spec
  • bundles latest version of swagger-ui and redoc for viewing the generated documentation
  • schema view is cacheable out of the box
  • generated Swagger schema can be automatically validated by swagger-spec-validator
  • supports Django REST Framework API versioning with URLPathVersioning and NamespaceVersioning; other DRF or custom versioning schemes are not currently supported
redoc screenshot

Fully nested request and response schemas.

swagger-ui screenshot

Choose between redoc and swagger-ui.

model definitions screenshot

Real Model definitions.

Table of contents

Usage

0. Installation

The preferred installation method is directly from pypi:

pip install -U drf-yasg

Additionally, if you want to use the built-in validation mechanisms (see 4. Validation), you need to install some extra requirements:

pip install -U drf-yasg[validation]

1. Quickstart

In settings.py:

INSTALLED_APPS = [
   ...
   'django.contrib.staticfiles',  # required for serving swagger ui's css/js files
   'drf_yasg',
   ...
]

In urls.py:

...
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi

...

schema_view = get_schema_view(
   openapi.Info(
      title="Snippets API",
      default_version='v1',
      description="Test description",
      terms_of_service="https://www.google.com/policies/terms/",
      contact=openapi.Contact(email="[email protected]"),
      license=openapi.License(name="BSD License"),
   ),
   public=True,
   permission_classes=[permissions.AllowAny],
)

urlpatterns = [
   re_path(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
   re_path(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
   re_path(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
   ...
]

This exposes 4 endpoints:

  • A JSON view of your API specification at /swagger.json
  • A YAML view of your API specification at /swagger.yaml
  • A swagger-ui view of your API specification at /swagger/
  • A ReDoc view of your API specification at /redoc/

2. Configuration

a. get_schema_view parameters

  • info - Swagger API Info object; if omitted, defaults to DEFAULT_INFO
  • url - API base url; if left blank will be deduced from the location the view is served at
  • patterns - passed to SchemaGenerator
  • urlconf - passed to SchemaGenerator
  • public - if False, includes only endpoints the current user has access to
  • validators - a list of validator names to apply on the generated schema; only ssv is currently supported
  • generator_class - schema generator class to use; should be a subclass of OpenAPISchemaGenerator
  • authentication_classes - authentication classes for the schema view itself
  • permission_classes - permission classes for the schema view itself

b. SchemaView options

  • SchemaView.with_ui(renderer, cache_timeout, cache_kwargs) - get a view instance using the specified UI renderer; one of swagger, redoc
  • SchemaView.without_ui(cache_timeout, cache_kwargs) - get a view instance with no UI renderer; same as as_cached_view with no kwargs
  • SchemaView.as_cached_view(cache_timeout, cache_kwargs, **initkwargs) - same as as_view, but with optional caching
  • you can, of course, call as_view as usual

All of the first 3 methods take two optional arguments, cache_timeout and cache_kwargs; if present, these are passed on to Django’s cached_page decorator in order to enable caching on the resulting view. See 3. Caching.

c. SWAGGER_SETTINGS and REDOC_SETTINGS

Additionally, you can include some more settings in your settings.py file. See https://drf-yasg.readthedocs.io/en/stable/settings.html for details.

3. Caching

Since the schema does not usually change during the lifetime of the django process, there is out of the box support for caching the schema view in-memory, with some sane defaults:

  • caching is enabled by the cache_page decorator, using the default Django cache backend, can be changed using the cache_kwargs argument
  • HTTP caching of the response is blocked to avoid confusing situations caused by being shown stale schemas
  • the cached schema varies on the Cookie and Authorization HTTP headers to enable filtering of visible endpoints according to the authentication credentials of each user; note that this means that every user accessing the schema will have a separate schema cached in memory.

4. Validation

Given the numerous methods to manually customize the generated schema, it makes sense to validate the result to ensure it still conforms to OpenAPI 2.0. To this end, validation is provided at the generation point using python swagger libraries, and can be activated by passing validators=['ssv'] to get_schema_view; if the generated schema is not valid, a SwaggerValidationError is raised by the handling codec.

Warning: This internal validation can slow down your server. Caching can mitigate the speed impact of validation.

The provided validation will catch syntactic errors, but more subtle violations of the spec might slip by them. To ensure compatibility with code generation tools, it is recommended to also employ one or more of the following methods:

swagger-ui validation badge

Online

If your schema is publicly accessible, swagger-ui will automatically validate it against the official swagger online validator and display the result in the bottom-right validation badge.

Offline

If your schema is not accessible from the internet, you can run a local copy of swagger-validator and set the VALIDATOR_URL accordingly:

SWAGGER_SETTINGS = {
    ...
    'VALIDATOR_URL': 'http://localhost:8189',
    ...
}
$ docker run --name swagger-validator -d -p 8189:8080 --add-host test.local:10.0.75.1 swaggerapi/swagger-validator
84dabd52ba967c32ae6b660934fa6a429ca6bc9e594d56e822a858b57039c8a2
$ curl http://localhost:8189/debug?url=http://test.local:8002/swagger/?format=openapi
{}

Using swagger-cli

https://www.npmjs.com/package/swagger-cli

$ npm install -g swagger-cli
[...]
$ swagger-cli validate http://test.local:8002/swagger.yaml
http://test.local:8002/swagger.yaml is valid

Manually on editor.swagger.io

Importing the generated spec into https://editor.swagger.io/ will automatically trigger validation on it. This method is currently the only way to get both syntactic and semantic validation on your specification. The other validators only provide JSON schema-level validation, but miss things like duplicate operation names, improper content types, etc

5. Code generation

You can use the specification outputted by this library together with swagger-codegen to generate client code in your language of choice:

$ docker run --rm -v ${PWD}:/local swaggerapi/swagger-codegen-cli generate -i /local/tests/reference.yaml -l javascript -o /local/.codegen/js

See the github page linked above for more details.

6. Example project

For additional usage examples, you can take a look at the test project in the testproj directory:

$ git clone https://github.com/axnsan12/drf-yasg.git
$ cd drf-yasg
$ virtualenv venv
$ source venv/bin/activate
(venv) $ cd testproj
(venv) $ python -m pip install -U pip setuptools
(venv) $ pip install -U -r requirements.txt
(venv) $ python manage.py migrate
(venv) $ python manage.py runserver
(venv) $ firefox localhost:8000/swagger/

Third-party integrations

djangorestframework-camel-case

Integration with djangorestframework-camel-case is provided out of the box - if you have djangorestframework-camel-case installed and your APIView uses CamelCaseJSONParser or CamelCaseJSONRenderer, all property names will be converted to camelCase by default.

djangorestframework-recursive

Integration with djangorestframework-recursive is provided out of the box - if you have djangorestframework-recursive installed.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].