Computer scienceBackendDjangoAPI

API documentation

3 minutes read

Imagine that you are going on a journey to an unknown land. You have a map, but it's in a language you can't read, and it lacks key details about the terrain, landmarks, or potential hazards. Navigating such a landscape would be perilous, time-consuming, and incredibly frustrating. Now, think of software development as a similar journey, and API documentation as your map. It becomes clear that you would want that map to be written in a language you understand and that it depicts the things you need right now. That's why documentation is a critical component of software development, the bridge between developers and the application. So, let's take a closer look at what the documentation is and how it can be implemented.

Why API documentation matters

API documentation is significant, but why? Why is it the cornerstone of successful software development? Here are a few reasons:

  • API development is a collaborative, lengthy process. Various team members work on different parts of the system. Dealing with a complex network of endpoints, methods, and data structures can create confusion. This is where API documentation can clarify things.

  • API documentation bridges the gap between developers and the application. It offers a clear, comprehensive guide on how to interact with your services and endpoints. Without proper documentation, developers may get lost in a web of unclear or outdated methods, leading to errors and wasted time.

  • API documentation expedites development. Solid documentation allows third-party developers to understand how to use your API quickly. This accelerates the development process, curtails the need for trial and error, and creates a shorter and more efficient path to the finished product.

Enhancing product quality is another critical aspect. When developers understand how to use your API correctly, the likelihood of errors and bugs decreases. Well-documented APIs contribute to more reliable and higher-quality applications, enhancing your product's user experience.

In today's software development world, we often rely on multiple third-party services and libraries. Clear, structured API documentation simplifies these integrations, facilitating smooth collaboration.

Even for the creators of the API, documentation serves as a handy self-reference. Sometimes, we might forget how our API works or how it has evolved over time. In these instances, documentation becomes our "notebook", aiding us in quickly recalling what methods and endpoints are available and their usage.

So, API documentation is a fundamental component of successful software development. It's an investment in productivity, quality, and collaboration. Lack of proper documentation can lead to missed opportunities and unnecessary roadblocks on the path to success. So, never underestimate the value of API documentation: it's your key to successful development.

OpenAPI Specification

OpenAPI Specification, also known as Swagger Specification, is a format for describing RESTful web services. It's used to document, test, and generate client and server code. The format describes the API structure and functionality, providing information about available endpoints, request parameters, response formats, authorization, and other web service aspects.

The OpenAPI Specification is a machine-readable JSON or YAML file that contains metadata about the API, including the API name and version, available endpoints, description of data formats used in requests and responses, plus examples thereof, and authorization methods required to access various parts of the API.

To use OpenAPI Specification, you should create a file with a .json or .yaml extension. You can then open this file in an editor and begin describing your API using OpenAPI syntax.

Here's the basic file structure for JSON:

{
  "openapi": "3.0.0",
  "info": {
    "title": "Cider API",
    "description": "Cider API description to fetch info about apple drinks",
    "version": "1.0.0"
  },
  "paths": {
    "/drinks/juice": {
      "get": {
        "summary": "Get the description of a juices and their types",
        "responses": {
          "200": {
            "description": "Successful response, returns cider description",
            "content": ...
          }
        }
      }
    }
  }
}

And for YAML:

openapi: 3.0.0
info:
  title: Cider API
  description: Cider API description to fetch info about apple drinks
  version: 1.0.0
paths:
  /drinks/juice:
    get:
      summary: Get the description of juices and their types
      responses:
        200:
          description: Successful response, returns cider description
          content:
            ...

Please note that there are three top-level parts in both examples: openapi, info, and paths. The openapi key, with its value set to 3.0.0, indicates which format is being used for the file. The info contains metadata related to your API, including a version tag that corresponds to your app's API version. The paths explain how to use the resources. You could consider them as destination descriptions, outlining what one can expect to find there.

Once the file is created, you can add to and update it as your API evolves. It's important to adhere to the OpenAPI Specification's structure and conventions. This ensures that tools and libraries using this file for documentation and code generation operate correctly. You can use various tools such as text editors, integrated development environments (IDEs), or specialized OpenAPI editors like Swagger Editor to edit OpenAPI Specification files.

Tools are also available to automatically generate documentation based on your OpenAPI Specification file. For example, the Swagger UI tool can generate interactive documentation that helps developers understand your API. Swagger UI creates a user-friendly web interface that automatically gathers information from the OpenAPI Specification file and presents it in a user-friendly way. This includes a list of available endpoints, request parameters, data formats, example requests and responses, and even information about authorization methods. Users can make HTTP requests directly from the Swagger UI, allowing them to test the API without needing to use third-party tools. They can specify query parameters and view the results in a convenient format.

To use Swagger UI, you must deploy it to a server and provide the path to your OpenAPI Specification file. After this, Swagger UI will be accessible through the browser for exploring and testing your API. It's beneficial to use Swagger UI in combination with the OpenAPI Specification to enhance the documentation and accessibility of their APIs for developers and users. More detailed information about Swagger UI's features and usage can be found on the official website.

While OpenAPI Specification provides superb tools for documenting and describing your API's structure, it's also vital to ensure that the data passed through the API is correct and consistent. In order to create a detailed and strict data specification, it's best to use the JSON Schema.

JSON Schema

JSON Schema is a vital tool in the world of API documentation that allows developers and users to understand the structure and format of the data that the application interface processes. This specification defines what data is valid in JSON format, establishing strict rules and restrictions for objects, fields, and their data types. JSON Schema not only clarifies documentation but also validates data, making API interaction reliable and predictable.

JSON Schema allows you to define what objects and fields are valid in a JSON document. You can specify the object structure, the data types for fields, and the acceptable values. It's used to verify if JSON data aligns with a given schema. If the data doesn't align with the schema, it's considered a validation error. You can learn more about the capabilities of JSON Schema on the official website.

The schema can specify what fields are required in a JSON document. This ensures that essential data is always present. It also allows you to establish rules and restrictions on data such as the minimum and maximum numbers, string lengths, regular expressions, among others.

Here's a JSON Schema example:

{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "age": { "type": "integer", "minimum": 0 },
    "email": { "type": "string", "format": "email" }
  },
  "required": ["name"]
}

JSON Schema can be used in various contexts, such as validating input data for APIs, generating automatic API documentation, validating data in a database, and much more. It's widely used to ensure the correctness and consistency of JSON data across different systems

With JSON Schema, you can describe both simple and complex data structures, determine required and optional fields, and set rules for values, easing the validation process. It's a handy tool in the development of web services, RESTful APIs, and data exchange between applications. The tool greatly simplifies the creation of API documentation, making it more informative and understandable for everyone involved. There are numerous tools, libraries, and frameworks for working with JSON Schema available for different programming languages.

However, you should keep in mind that validating data against a schema may require additional resources and slow down the processing of API requests and responses, especially for intricate schemas and large volumes of data. Also, JSON Schema is suitable for describing data structure but may not cover business logic and complex validations required in some applications.

Despite these shortcomings, JSON Schema remains a precious tool for giving structure and reliability to JSON data. Additionally, Python can facilitate interaction with JSON Schema regardless of the framework involved, as evidenced by the JSON Schema specification for Python. However, for API developers and users to reap the most benefits from this structure, it's crucial to document the API clearly and accurately. Let's explore how to create readable and informative API documentation based on Django REST Framework (DRF).

JSON Schema provides a handy tool for defining data structure and validating it, ensuring your API is reliable and consistent. However, creating helpful documentation that guides your API users in understanding how to interact with it is equally essential. Let's examine practical techniques and tools for crafting informative and useful API documentation using the Django REST framework.

How to document in DRF

There are several ways to implement documentation in DRF. DRF offers a Browsable API that automatically creates interactive documentation. This tool is based on well-documented code. If you've used annotations, comments, and other attributes to describe your API, the documentation will generate automatically. Developers can then explore available endpoints, submit requests, and view responses via a browser interface. This is a handy solution for initial API documentation.

To use the Browsable API, add it to the REST framework settings by setting the DEFAULT_RENDERER_CLASSES parameter to rest_framework.renderers.BrowsableAPIRenderer. This setting will render your API as a web page with interactive contents, which include forms, links, and buttons:

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ],
}

When you visit your server's home page, you'll see interactive Browsable API documentation. The documentation will list available endpoints, and you can use it to query these, explore the data, and submit test data to create and update resources. For instance, a movies API's documentation might look like this:

Browsable API example

If you need more detailed and informative documentation, consider using DRF-extensions. This add-on provides tools for generating API documentation. It uses JSON Schema and OpenAPI to generate automated documentation that details available endpoints, query parameters, and data formats. This type of documentation is particularly useful for developers needing to understand how to interact with your API.

To use DRF-extensions, you need to install it:

pip install drf-extensions

Then, add rest_framework_extensions to the INSTALLED_APPS in your project's settings.py file. After this, add rest_framework_extensions.docs.urls to the list of urlpatterns in your project's urls.py file:

from django.conf.urls import url, include

urlpatterns = [
    path(r'^', include('rest_framework_extensions.docs.urls')),
]

Lastly, add the @extend_schema_with_generic_viewset_and_routes decorator to the viewsets you want to document. This decorator lets you automatically generate a schema for viewsets and their additional actions:

from rest_framework import viewsets
from rest_framework_extensions.decorators import extend_schema_with_generic_viewset_and_routes

@extend_schema_with_generic_viewset_and_routes()
class UserViewSet(viewsets.ModelViewSet):
  # viewset logic

Now, you can visit /docs/ in your browser to see your API's generated documentation. You can also customize the looks and contents of the documentation using various options in the REST_FRAMEWORK_EXTENSIONS dictionary. For more information, refer to the documentation.

DRF-extensions is useful in projects where fast automatic documentation generation and easy integration with Swagger are important. However, other tools and libraries also provide good ways to create API documentation in DRF. The choice depends on your project's specific requirements.

Conclusion

API documentation serves as a bridge between developers and the application, offering clear guidance on how to interact with services and endpoints. It accelerates the development process, enhances product quality, simplifies integration with other systems, and serves as a useful reference for API creators.

OpenAPI Specification provides a format for describing RESTful web services, simplifying the task of creating and maintaining documentation. JSON Schema allows you to define data structure and format, increasing API reliability, and providing clear documentation.

Selecting documentation tools and methods that suit your project's specific requirements is key. From the auto-generated Browsable API to more detailed documentation using DRF-extensions, there are various ways to ensure your API documentation is clear and accessible to developers and users.

In conclusion, correct and clear API documentation is key to successful development, increasing productivity and ensuring high-quality system interaction. Never underestimate the value of API documentation - it's your reliable guide to success in the world of development.

3 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo