© Anand Tamboli 2019
Anand TamboliBuild Your Own IoT Platformhttps://doi.org/10.1007/978-1-4842-4498-2_11

11. Documentation and Testing

Anand Tamboli1 
(1)
Sydney, NSW, Australia
 

Good documentation accelerates the development and consumption of the developed resources. It also reduces the money and time that would otherwise be spent in answering support calls. The documentation is usually considered part of the overall user experience. Complete and accurate documentation is always a key to saving resources and improving the efficiency and effectiveness of API usage.

The obvious question stemming from this point is how can we document our IoT platform’s API in an effective way? One of the most preferred ways is to use freely available or open source tools for documenting APIs. There are several options, which you can find at https://nordicapis.com/ultimate-guide-to-30-api-documentation-solutions/ .

We will use Swagger tools for generating our API documentation. It is easy to create interactive documentation while effortlessly maintaining it on the go with Swagger. More importantly, you can either host the interface (definition and sandbox) on the Swagger hub, or you can integrate it as a standalone on an independent cloud instance. This is what we will do in our case.

In this chapter, we will
  • Discuss how to prepare an OpenAPI specification

  • Clone and update a Swagger package

  • Test API docs in a live environment

Preparing a Valid OpenAPI Specification Document

The first step in creating useful documentation is to create an API description document in a valid format. Since Swagger uses OpenAPI specifications that can be documented using the YAML format, we will create that at the outset.

YAML (YAML Ain’t Markup Language) is a human-readable data serialization language. It is commonly used for configuration files but could be used in many applications where data is being stored (e.g., debugging output) or transmitted (e.g., document headers).

If you are interested in learning more about the OpenAPI format and specifications, there are plenty of tutorials on the Internet. Some are easily available on the Swagger website as well.

The Swagger online editor is another open source and free tool that can be used to validate the specification document we are preparing; alternatively, we can make one from scratch in the same editor. This editor is available at https://editor.swagger.io/#/ .

While writing this book, I created an API specification document (api.yml), which you can access from GitHub. Download the file, which is in .yml (i.e., YAML format). Paste the contents of the file into the Swagger online editor, and make sure that there are no warnings or errors. What you see in the view on the right of the Swagger editor is a fully functional user interface that will be the actual output after deployment.

You can play with the document, make some changes, and see how they affect the output. Once finished, you can copy and paste the file content back to the local copy for further usage.

Platform API Specification File Explained

Now let’s refer to our platform API file contents and learn about the file structure in detail.
swagger: '2.0'
info:
  title: in24hrs.the.book
  description: This page provides documentation and also serves as a test sandbox for     **in24hrs** platform.
    **w:** [www.in24hrs.xyz](https://www.in24hrs.xyz)
    **e:** [email protected]
  version: "1.0.1"
schemes:
  - https
host: 'www.in24hrs.xyz:1880'
basePath: /

The first line states the version of the API specification, which in our case is 2.0. The following lines provide some description about the document, which will also be shown on the user interface. We specified which API calling scheme our API will follow; it has been fixed to HTTPS only. The definitions of Host and basepath specify the base URL for our API.

Also note that any comments in this file begin with the # character, so the entire line is treated as a comment.
securityDefinitions:
  Bearer:
    type: apiKey
    name: authorization
    in: header
The next set of lines defines the security/authentication scheme for our API. In the previous chapter, we added a bearer authentication to our API and created a scheme where this has to be passed in the authorization header. These lines define this scheme such that when we use this interactive API UI, we can provide authentication details to it.
paths:
#--------------------------------------------------------------
# 1 Data publishing API
#--------------------------------------------------------------
  /pub/{topic}/{payload}:
    post:
      description: 'create a new data {payload} for a {topic}'
      security:
        - Bearer: []
      tags:
        - '1 Data publishing API'
      parameters:
        - name: topic
          in: path
          description: 'Topic to publish data for'
          type: string
          required: true
        - name: payload
          in: path
          description: 'Message payload for given topic, could be plain text, binary, json, or any other format'
          type: string
          required: true
      responses:
        '200':
          description: 'Response to post/publish operation'
          schema:
            type: object
            properties:
              success:
                type: boolean
                description: 'Success status of operation'
              message:
                type: object
                description: 'Additional response text'

After those base definitions, we start defining our API’s endpoints. Our first data publishing API /pub is shown here. Notice how we have enabled authentication for the first API, and subsequently, this will be used for each API definition.

The rest of the contents are self-explanatory, which is also an advantage due to the usage of the YAML format. You can use any text editor for editing this file locally; however, I recommend online editing using the Swagger UI editor because it can help you check for errors and warnings while you edit. As a next step, head over to the Swagger UI GitHub page at https://github.com/swagger-api/swagger-ui . Then, click Clone or the Download button, and select the Download ZIP option, refer to Figure 11-1 for more details. Download the files to a convenient location on your computer and extract them.
../images/474034_1_En_11_Chapter/474034_1_En_11_Fig1_HTML.jpg
Figure 11-1

Download Swagger-UI files to your local computer

Since we are not going to compile the source, but only use the UI part of it, we will not need the entire downloaded package. Locate the dist folder in extracted files. Copy and paste this folder out of the main folder and place it in a standalone directory. At this point, you can safely delete the rest of the extracted package if you wish to.

Preparing Distribution Package for Final Upload

At this stage, if you already downloaded the api.yml file, place this file in the dist folder that we separated. There is a file named index.html in the dist folder, which now can be opened for editing in any text editor.

Locate the JavaScript section in the index.html file and edit it as follows.
const ui = SwaggerUIBundle({
url: "http://petstore.swagger.io/v2/swagger.json",
dom_id: '#swagger-ui',
Change the URL to our API specification file as
const ui = SwaggerUIBundle({
url: "api.yml",
dom_id: '#swagger-ui',

Now let’s change the name of the folder (from dist) to docs for convenience; you can change it to any name you want though. With this change, our API specification package is ready for upload.

Upload API Docs and Make It Live

Now connect to our cloud instance over FTTP using FileZilla or any other FTTP tool and upload this (docs) folder to the /var/www/html/ directory. This is our cloud instance’s web directory and our index.php file should be visible here already. Once all the files are uploaded, head over to the cloud instance web URL ( www.in24hrs.xyz/docs ) in your browser and see for yourself. Our API documentation is now live and should look similar to what is shown in Figure 11-2.
../images/474034_1_En_11_Chapter/474034_1_En_11_Fig2_HTML.jpg
Figure 11-2

Live API documentation page

Note the Authorize button at the top of the API. It is for providing authorization details to the UI. If you use the API now, especially the data reading API, you will not get anything in the output, because not providing authentication yields empty output.

The lock icons on each of the API listings indicate that authorization is required.

Authorize and Test API

In Chapter 10, we established a token-based API authorization and authentication. This expects an authorization header with contents as Bearer <token>, where token is an alphanumeric string used for a unique identification of the API caller.

To provide this information in our live Swagger UI, click the Authorize button, which opens an authorizations dialog box asking for value input, as shown in Figure 11-3. Note that we are adding the keyword, Bearer, at the beginning of this value input with a space, followed by our access token. Once we press the Authorize button, the dialog box will show that you are logged in with given authorization information. The lock icons on the API headings change, as shown in Figure 11-3.
../images/474034_1_En_11_Chapter/474034_1_En_11_Fig3_HTML.jpg
Figure 11-3

Providing authorization in Swagger UI

If you want to test with a different authorization token, simply click the Authorize button, press Logout, and reauthorize with the new token.

There are several UI configuration parameters, which are explained in the Swagger documentation. These parameters could be utilized to make this UI more interactive and customized to your liking. It will not affect or change anything in the API specification file. If you spend enough time beautifying it, you can take it to a whole new level. However, at this stage, you should be able to test various APIs in our IoT platform on this page.

We now have our API clearly documented and available for developers or users to test interactively. Whenever you add any new endpoint to the platform, you can update the YAML definition in the api.yml file, and the UI will update with a new set of specifications.

Summary

In this chapter, we discussed the documentation method and created an API document for our own platform. Until this point, we had a fully working IoT platform along with the required documentation and all the core functionalities that we planned in the initial chapters. We also established a good and extensible framework, which we can keep improving and expanding as the development, usage, and overall business progresses without disrupting what is working.

In the next chapter, we review what we did throughout, and more importantly, why we did it! I also address a few commonly asked questions in various forums and discuss a few advancements that are in progress, which you might want to add to the platform when you build it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.53.5