Tutorial on How to Write and Use Swagger API - bounswe/bounswe2024group11 GitHub Wiki

Description

Swagger provides a way to document APIs in a machine-readable format, typically using JSON or YAML. The documentation includes details such as available endpoints, request parameters, response formats, authentication methods, and more. This tutorial is a step-by-step guide on how to specify these details using openapi library. For openapi specifications, refer to Open API Specifications

How to Use Swagger UI

  • Swagger UI can currently be accessed on <host>/user/swagger
  • You can read the description of the API.
  • You can read the response codes that the API can return and their descriptions.
  • You can use the API by clicking the button Try it out on the right upper corner.
  • After that, you can send JSON data.
  • Here is an example Swagger UI: image

Step-by-Step Guide on How To Implement

  1. pip install drf_yasg
  2. add 'drf_yasg', to INSTALLED_APPS = [ ... ] in settings.py
  3. in urls.py add
schema_view = get_schema_view(
    openapi.Info(
        title="Your title",
        default_version='your version',
        description="your description",
        #terms_of_service="https://www.google.com/policies/terms/",
        #contact=openapi.Contact(email="[email protected]"),
        #license=openapi.License(name="BSD License"),
    ),
    public=True,
)

and path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui') to urlpatterns list.

    • in views.py file from drf_yasg.utils import swagger_auto_schema and from drf_yasg import openapi and at the beginning of each API endpoint, add swagger_auto_schema:
@swagger_auto_schema(
    method='post', # whether it is post or get etc
    operation_summary="your summary",
    operation_description="your description.",
    request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        properties={
            'property1': openapi.Schema(type=openapi.TYPE_STRING),
            'property2': openapi.Schema(type=openapi.TYPE_INT)
        },
        required=['property2']
    ),    responses={
        201: "Created",
        400: "Bad Request"
    },
    operation_id='op_id',
)
⚠️ **GitHub.com Fallback** ⚠️