DEV Community

Cover image for DRF-YASG: The Superhero of API Documentation - Saving Developers from Documentation Despair!
Aditya Mathur
Aditya Mathur

Posted on • Edited on

DRF-YASG: The Superhero of API Documentation - Saving Developers from Documentation Despair!

In the midst of a migration project at my workplace, where we are transitioning a web application from the .NET framework to a Python + React architecture, we encountered a significant challenge that impeded our progress: the absence of comprehensive and up-to-date API documentation. As we started this technology stack migration, it became increasingly crucial to understand the logic behind data point validation when developing APIs. However, the lack of accurate and up-to-date API documentation proved to be a major obstacle.

Throughout my years of experience, I've come to realize that maintaining APIs can be a daunting task. It requires constant effort and attention to ensure they meet evolving business requirements and remain in sync with the ever-changing technological landscape. In my journey, I have encountered several significant challenges that have tested my ability to effectively maintain APIs. Let's explore these challenges.

Challenges

  1. Consistency and Accuracy
    Maintaining consistency and accuracy in API documentation is crucial. However, it can be challenging to ensure that the documentation accurately reflects the current state of the API. As updates and changes are made, keeping the documentation in sync becomes a demanding task.

  2. Handling API Changes
    As business needs evolve, APIs must adapt accordingly. Introducing changes to APIs while minimizing disruption to existing integrations can be intricate. Properly communicating and managing these changes to minimize the impact on consumers of the API is vital.

  3. Documentation Complexity
    APIs can have intricate workflows, numerous endpoints, and various input/output parameters. Documenting such complexity in a clear and concise manner can be demanding. Striking the right balance between providing sufficient detail for developers while maintaining simplicity can be a significant challenge.

  4. API Governance and Security
    Establishing and maintaining proper API governance and security measures is essential to protect sensitive data and prevent unauthorized access. Implementing secure authentication and authorization mechanisms, managing access control, and monitoring API usage require ongoing attention and vigilance.

In my quest to find better solutions for addressing the challenges of API maintenance, I came across DRF-YASG (Django Rest Framework - Yet Another Swagger Generator). This powerful tool simplifies the process of generating and maintaining API documentation, offering a comprehensive solution for tackling the challenges I previously faced.

1. Introduction (What is DRF-YASG)
DRF-YASG, short for Django Rest Framework - Yet Another Swagger Generator, is a remarkable tool that simplifies the process of generating and maintaining API documentation. Specifically designed for Django Rest Framework, DRF-YASG automates the generation of interactive API documentation based on the OpenAPI specification (formerly known as Swagger).

2. Why DRF-YASG?
DRF-YASG can serve as a single solution for all the challenges that I mentioned above.

  • Consistency and Accuracy
    DRF-YASG simplifies the process of generating API documentation by automatically extracting information from Django Rest Framework's serializers, views, and viewsets. This ensures that the documentation remains consistent with the actual implementation of the API, reducing the risk of inconsistencies and inaccuracies.

  • Handling API Changes
    DRF-YASG automatically updates the API documentation when changes are made to the underlying Django Rest Framework codebase. This helps in keeping the documentation in sync with the API's current state, even when introducing changes such as adding or modifying endpoints, parameters, or response structures.

  • Documentation Complexity
    DRF-YASG generates interactive and user-friendly documentation based on the OpenAPI specification (formerly known as Swagger). It handles the complexity of documenting intricate workflows, endpoints, and parameters, providing a clear and intuitive interface for developers to understand and interact with the API.

  • API Governance and Security
    DRF-YASG supports the integration of authentication and authorization mechanisms provided by Django Rest Framework, making it easier to enforce API governance and security measures. It enables the inclusion of authentication schemes, permissions, and access control details in the generated documentation, promoting secure API usage.

3. Adding DRF-YASG to Django: Unlock the Swagger Magic

  • Step 1: Install DRF-YASG

Start by installing DRF-YASG into your Django project. You can do this using pip, the Python package manager, by running the following command:



pip install drf-yasg


Enter fullscreen mode Exit fullscreen mode
  • Step 2: Configure Django Rest Framework

To enable DRF-YASG, ensure that you have Django Rest Framework properly configured in your Django project. This involves adding the necessary packages and settings to your settings.py file.
You need to add DRF-YASG in your installed apps in project's settings.py file.



INSTALLED_APPS = [
    ...Rest of Installed Apps
    'drf_yasg'
]


Enter fullscreen mode Exit fullscreen mode
  • Step 3: Include DRF-YASG URLs Next, you need to include DRF-YASG URLs in your Django project's URL configuration. Open your project's urls.py file and add the following import statement at the top:


from drf_yasg.views import get_schema_view
from drf_yasg import openapi


Enter fullscreen mode Exit fullscreen mode

Then, create a schema view and configure it with your API information. Add the following code to your urls.py file:



schema_view = get_schema_view(
   openapi.Info(
      title="Your API Title",
      default_version="v1",
      description="Your API description",
      terms_of_service="https://example.com/terms/",
      contact=openapi.Contact(email="contact@example.com"),
      license=openapi.License(name="MIT License"),
   ),
   public=True,
)

urlpatterns = [
   # Your existing URL patterns
   # ...
   path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
   path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
]



Enter fullscreen mode Exit fullscreen mode
  • Step 4: Update your APIs If you have a Django view function or a class-based view representing your API endpoint. You can add the @swagger_auto_schema decorator above this view function or class to provide additional Swagger documentation.


@swagger_auto_schema(
    method='post',
    request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        properties={
            'name': openapi.Schema(type=openapi.TYPE_STRING),
            'email': openapi.Schema(type=openapi.TYPE_STRING),
        },
        required=['name', 'email']
    ),
    responses={
        201: 'Created',
        400: 'Bad Request',
    }
)
@api_view(['POST'])
def create_user(request):
    # Your implementation here
    pass


Enter fullscreen mode Exit fullscreen mode

Here's what each argument in the decorator does:

  1. method: Specifies the HTTP method(s) for which the Swagger documentation should be generated. In this case, we set it to 'post' to document the POST method.

  2. request_body: Describes the request body schema for the API endpoint. We define an object schema with two properties, name and email, both of type string. We also specify that both properties are required.

  3. responses: Defines the expected responses for the API endpoint. In this case, we specify a 201 response for a successful creation and a 400 response for a bad request.

You can customize the request_body and responsesaccording to your specific API endpoint requirements.

  • Step 5: Accessing your swaggered APIs & its docs:

Congratulations, you have successfully swaggered up your APIs. Now you can focus on developing the API end points and let DRF-YASG take the task for documentation.

You can access the swagger UI from the endpoints you created in your urls.py.

Below picture shows how the UI of the swaggerand the redoclooks like:

  1. Swagger UI:
    Swagger UI

  2. redoc UI:
    redoc UI

Swagger UI provides a range of features and functionalities that allow you to interact with and explore APIs. Here are some of the main things you can do in Swagger UI:

  1. Browse API Endpoints: Swagger UI presents a list of available API endpoints, making it easy to navigate and find the desired endpoint.

  2. View API Documentation: Swagger UI displays detailed documentation for each API endpoint, including the request parameters, headers, and response schemas.

  3. Test API Calls: You can make API calls directly from Swagger UI by entering the required parameters and executing the request. The response is displayed within the interface.

  4. Select HTTP Methods: Swagger UI supports various HTTP methods (GET, POST, PUT, DELETE, etc.) for API calls. You can choose the appropriate method for each endpoint.

  5. Provide Request Parameters: Swagger UI allows you to enter the necessary parameters for an API call, such as query parameters, path parameters, and request body data.

  6. Configure Request Headers: You can set custom headers for API requests, such as authentication tokens or content types.

  7. Handle Authentication: Swagger UI provides options to handle authentication, including basic authentication, API key authentication, or OAuth. You can enter the required credentials or tokens for authenticated endpoints.

  8. Handle Response Codes: Swagger UI displays the possible response codes for each API call. You can view the response code, description, and associated response schema.

  9. View Request Examples: Swagger UI can show request examples, allowing you to see the expected structure and format of the request payload.

  10. View Response Examples: Swagger UI can display response examples, showing sample responses based on the response schema.

  11. Interact with Enumerated Values: If an endpoint has enumerated values for certain parameters, Swagger UI provides dropdowns or auto-complete options to select the appropriate values.

  12. Handle Pagination: If an API supports pagination, Swagger UI provides options to specify page size and navigate through the paginated results.

  13. Save and Share Requests: Swagger UI allows you to save and share API requests, making it convenient for collaboration or documentation purposes.

  14. Download API Definition: Swagger UI provides options to download the OpenAPI/Swagger specification file (in JSON or YAML format) for the API.

  15. Search Functionality: Swagger UI includes a search bar that lets you quickly search for specific endpoints, parameters, or operations within the API documentation.

  16. Switch between API Versions: If multiple versions of an API are documented, Swagger UI allows you to switch between different versions to explore the endpoints specific to each version.

Conclusion:

In conclusion, DRF-YASG is an essential tool for documenting Django APIs. Its integration with Django REST Framework and the ability to generate interactive API documentation using OpenAPI (Swagger) specifications make it a valuable asset for developers. With DRF-YASG, you can save time, create comprehensive documentation, and enhance the overall developer experience of your API.

Thank you for reading! If you have any questions or feedback about this article, please don't hesitate to leave a comment. I'm always looking to improve and would love to hear from you.

Also, if you enjoyed this content and would like to stay updated on future posts, feel free to connect with me on LinkedIn or X or check out my Github profile. I'll be sharing more tips and tricks on Django and other technologies, so don't miss out!

If you find my content valuable and would like to support me, you can also buy me a coffee. Your support helps me continue creating helpful and insightful content. Thank you!

Top comments (1)

Collapse
 
jsabater profile image
Jaume Sabater

Hey there, and thanks for your tutorial! A question I have not been able to find an answer for in the DRF-YASG docs: When creating a schema view in urls.py and configuring it with the API information, the description field is always populated with a short description of the project.

If you would like to have some sort of index.md file (or similar) where you would welcome the developer, introduce him/her to how the API works and how to use it, and talk about topics such as versioning, authentication, use policy, response codes, etc., how would you link your description field to that file?

In your example above, you show screenshots of Swagger UI and reDoc (steps 5.1 and 5.2, respectively). By using three double-quotes I've been able to greatly expand the description field but it's become unbearable.

Alternatively, were that not be the right place for it, how would you sort out such scenario?

Thanks in advance.