Reader small image

You're reading from  Building Enterprise JavaScript Applications

Product typeBook
Published inSep 2018
Reading LevelIntermediate
PublisherPackt
ISBN-139781788477321
Edition1st Edition
Languages
Right arrow
Author (1)
Daniel Li
Daniel Li
author image
Daniel Li

Daniel Li is a full-stack JavaScript developer at Nexmo. Previously, he was also the Managing Director of Brew, a digital agency in Hong Kong that specializes in MeteorJS. A proponent of knowledge-sharing and open source, Daniel has written over 100 blog posts and in-depth tutorials, helping hundreds of thousands of readers navigate the world of JavaScript and the web.
Read more about Daniel Li

Right arrow

Chapter 13. Documenting Our API

So far, we have followed a test-driven approach to developing our User Directory application. We started by writing End-to-End (E2E) tests and using them to drive the development of our implementation code, and then added unit tests to catch regressions. We have also discussed that writing tests is the best form of documentation, since it provides actual examples of how to interact with our API.

While our test suite is the most accurate and best form of documentation, providers of all major APIs also maintain browser-based API documentation that your end users can access as a web page/site. This is because:

  • Not all APIs are open-sourced, so developers may not always have access to the tests.
  • It may require a lot of time and effort to understand the test suite.
  • Tests lack context—you know how to call an endpoint, but you will have to figure out for yourself how it fits into the workflow of an application.
  • It is language- and framework-specific—the browser-based...

Overview of OpenAPI and Swagger


An API description language (or API description format) is a standard format for describing APIs. For example, the snippet below informs the consumers of our API that they need to provide a JSON payload with an email and digest field when calling the POST /login endpoint. In return, they can expect our API to respond with one of the four listed status codes:

paths:
  /login:
    post:
      requestBody:
        description: User Credentials
        required: true
        content:
          application/json:
            schema:
              properties:
                email:
                  type: string
                  format: email
                digest:
                  type: string
                  pattern: ^\\$2[aby]?\\$\\d{1,2}\\$[.\\/A-Za-z0-9]{53}$
      responses:
        '200':
          $ref: '#/components/responses/LoginSuccess'
        '400':
          $ref: '#/components/responses/ErrorBadRequest'
        '401':
          $ref: '#/components...

Defining an API specification with OpenAPI


Now that we understand what an API specification and the OpenAPI standard are, as well as the tooling provided by Swagger, let's begin the documentation process by writing the specification for our API. We'll start by creating a file new at src/spec/openapi/hobnob.yaml:

$ mkdir -p spec/openapi
$ touch spec/openapi/hobnob.yaml

Learning YAML

The first thing to know is that an OpenAPI specification must be a valid JSON document. The specification also explicitly allows YAML, which is a superset of JSON and can be converted to JSON. We will be using YAML because it is more readable (and thus writable) by humans, even for non-developers. Furthermore, you can add comments inside YAML files, something that's not possible with JSON.

Let's start by learning the basics of YAML. We only need to learn a few basic pieces of syntax to write our OpenAPI specification.

Like JSON, getting started with the basic syntax for YAML is very simple. All YAML documents start...

Generating documentation with Swagger UI


We now have a valid OpenAPI specification, which we can use to generate web-based API documentation using Swagger UI.

Adding the Swagger UI to our repository

The Swagger UI source files are located in the dist/ directory of the official repository. The official way of generating documentation UI for our own specification is to download the Swagger UI source files from github.com/swagger-api/swagger-ui/releases and statically serve the page at dist/index.html.

However, it'll more preferable to have the source code of the web UI in the same repository as our API. A naive approach would be to download the latest source files for Swagger UI from github.com/swagger-api/swagger-ui/releases, unpack the contents, and copy the contents of the dist/ directory into a docs/ directory inside our repository. However, this requires us to manually update the contents of the docs/ directory each time there's an update on Swagger UI; obviously, that's not ideal. Luckily...

Deployment


Lastly, let's go into our remote server and deploy our documentation site. We do this by pulling in our changes and installing the dependencies.

$ ssh hobnob@142.93.241.63
hobnob@hobnob:$ cd projects/hobnob/
hobnob@hobnob:$ git fetch --all
hobnob@hobnob:$ git reset --hard origin/master
hobnob@hobnob:$ yarn

Next, we'll also need to generate a new set of keys and set the SWAGGER_UI_* environment variables inside the .env file:

SWAGGER_UI_PROTOCOL=http
SWAGGER_UI_HOSTNAME=docs.hobnob.social
SWAGGER_UI_PORT=80
PRIVATE_KEY="..."
PUBLIC_KEY="..."

Then, run the docs:update script to generate the static files which would be served by NGINX. To give NGINX access to these files, we should also update the owner and group of the docs directory to nginx:

hobnob@hobnob:$ yarn run docs:update
hobnob@hobnob:$ sudo chown -R nginx:nginx ./docs/*

Then, restart the API server:

hobnob@hobnob:$ npx pm2 delete 0
hobnob@hobnob:$ yarn run serve

After this, add a new virtual host definition at /etc/nginx/sites...

Summary


In this chapter, we used the OpenAPI specification format to document our API and used Swagger UI to transfer that specification into a user-friendly web page.

This concludes the work we need to do for our back-end code. In the next chapter, we will build the front-end user interface that will interact with our API.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Building Enterprise JavaScript Applications
Published in: Sep 2018Publisher: PacktISBN-13: 9781788477321
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Daniel Li

Daniel Li is a full-stack JavaScript developer at Nexmo. Previously, he was also the Managing Director of Brew, a digital agency in Hong Kong that specializes in MeteorJS. A proponent of knowledge-sharing and open source, Daniel has written over 100 blog posts and in-depth tutorials, helping hundreds of thousands of readers navigate the world of JavaScript and the web.
Read more about Daniel Li