Document the APIs with Swagger (3/4) — Setting up the environment

In this series of articles, I will introduce the different Swagger tools. Swagger is a very handy tool for API documentation. It allows you to generate “living” documentation, so that the documentation is always up to date, which is very difficult to do without this kind of tool. It also allows to generate code automatically, allowing the developer to focus on his core business. Finally, it is based on an open source specification format.

These articles focus on Swagger 2.0, while the 3.0 version (“OpenAPI 3.0.0”) is available.

This article is thus broken down into four parts :

  • Introduction,
  • The Swagger framework,
  • Setting up the set,
  • The API test.

There are two ways to use the documentation:

  • by Swagger UI embedded in the server,
  • or by Swagger UI running autonomously.

Use of Swagger UI embedded in the server

Setting up the environment

docker run \
    --rm \
    -v ${PWD}:/local \
    swaggerapi/swagger-codegen-cli \
    generate -i /local/swagger.yaml -l nodejs-server -o /local/out

The result of the command is:

[main] INFO io.swagger.parser.Swagger20Parser - reading from /local/swagger.yaml
[main] INFO io.swagger.codegen.DefaultCodegen - Skipped overwriting index.js as the file already exists in /local/out//index.js
[main] INFO io.swagger.codegen.DefaultCodegen - Skipped overwriting package.json as the file already exists in /local/out//package.json
[main] INFO io.swagger.codegen.DefaultCodegen - Skipped overwriting README.md as the file already exists in /local/out//README.md
[main] WARN io.swagger.codegen.languages.NodeJSServerCodegen - 'host' in the specification is empty or undefined. Default to http://localhost.
[main] WARN io.swagger.codegen.DefaultGenerator - 'host' not defined in the spec. Default to 'localhost'.
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/service/ContactService.js
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/controllers/Contact.js
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/utils/writer.js
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/api/swagger.yaml
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/.swagger-codegen/VERSION

Install the dependencies:

cd out/
npm install

The output of the command is:

npm WARN deprecated superagent@1.8.5: Please note that v5.0.1+ of superagent removes User-Agent header by default, therefore you may need to add it yourself (e.g. GitHub blocks requests without a User-Agent header).  This notice will go away with v5.0.2+ once it is released.
        ░░░░░░⸩ ⠹ install:methods: info lifecycle methods@1.1.2~install: m[0m
> core-js@2.6.9 postinstall /Users/brunodelb/devops/notebooks/documentation/Swagger/out/node_modules/core-js
> node scripts/postinstall || echo "ignore"
Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!
The project needs your help! Please consider supporting of core-js on Open Collective or Patreon: 
> https://opencollective.com/core-js 
> https://www.patreon.com/zloirock 
Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)
npm notice created a lockfile as package-lock.json. You should commit this file.[K
added 147 packages from 83 contributors and audited 401 packages in 4.223s
found 5 vulnerabilities (2 low, 2 moderate, 1 high)
  run `npm audit fix` to fix them, or `npm audit` for details

Launch the server:

node index.js

NodeJS indicates that the server is running by specifying the listening port:

Your server is listening on port 8080 (http://localhost:8080)
Swagger-ui is available on http://localhost:8080/docs

Checking that the server is properly installed

Check that the server responds correctly:

  • Go to the documentation at http://0.0.0.0:8080/docs.
  • Click Contact.
  • Click on the GET /contact route.
  • Click on Try it out!
  • The Response Body frame displays no content: the result is empty.

This is normal. We will modify the server source code to return data.

Modification of the server to return data

Stop the NodeJS server.

Edit the file ./out/service/ContactService.js and replace the :

examples['application/json'] = "";

by:

examples['application/json'] = [
        {"id": 1, "name": "Toto"}
    ];

Restart NoteJS :

node index.js

NodeJS confirms that the server is restarted:

Your server is listening on port 8080 (http://localhost:8080)
Swagger-ui is available on http://localhost:8080/docs

Verify that the server is returning data as expected

Verify that the server is returning data:

  • Return to http://0.0.0.0:8080/docs.
  • Refresh the page.
  • Click on Contact.
  • Click on the GET /contact route.
  • Click on Try it out!
  • The Response Body frame displays :
[
  {
    "name": "Toto"
  }
]

So Swagger displays well the data we have added in the API.

Using Swagger UI running autonomously

This scenario corresponds to the case where the server source code was not generated by Swagger Codegen CLI.

We have already created the specifications. You must have specified the host with its port and the scheme (HTTP or HTTPS) in the specifications.

Launch the REST API server:

node index.js

The result of the command is:

Your server is listening on port 8080 (http://localhost:8080)
Swagger-ui is available on http://localhost:8080/docs

Start the Swagger UI server:

docker run \
    -d \
    -p 83:8080 \
    -e SWAGGER_JSON=/app/swagger.yaml \
    -v $PWD:/app \
    swaggerapi/swagger-ui

The result of the command is:

c5e469bd19e91578bee821a61d18d9dbaa5d5d58005a27c7c2836b0b8a867fa1

Verify that the API call to display the contact list fails

  • Go to the documentation at http://0.0.0.0:83.
  • Click on the Get the list of contacts line.
  • Click Try it out.
  • Click Execute.

An error message is displayed in the Chrome browser console: blocked by CORS policy.

You must enable CORS in the NodeJS server.

Activation of CORS in the NodeJS server

Edit the index.js file and add the following code before the line // Initialize the Swagger middleware:

app.use(function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
  res.setHeader('Access-Control-Allow-Credentials', true);
  next();
});

Run the request again in Swagger: the error message in the web browser disappears.

The Response Body frame then displays:

[
  {
    "name": "Toto"
  }
]

The Swagger framework is based on OpenAPI Specification.

The specifications are written in YAML or JSON.

Swagger includes several sub-projects responding to a specific objective:

  • Swagger Editor: to edit specification files in YAML format;
  • Swagger UI: to display and run Swagger specification files interactively;
  • Swagger CodeGen: to read specification files and generate client and server skeleton code.

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×