Document the APIs with Swagger (2/4) — The framework Swagger

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.

The Swagger framework (https://github.com/swagger-api) includes several sub-projects that meet a specific objective. Here are the ones we will discuss here:

  • Swagger Editor,
  • Swagger UI,
  • Swagger CodeGen.

Swagger Editor

Swagger Editor (https://github.com/swagger-api/swagger-editor) allows to edit specification files in YAML format. In other words, it allows you to create a contract.

Launch Swagger Editor :

docker run \
    -d \
    -p 82:8080 \
    swaggerapi/swagger-editor

The output of the command is:

32cb780d106341769f19a72f5489b463030d8f62860dce392dae414ec89695b3

Then in a web browser, go to http://0.0.0.0:82.

Import specifications

To import the Swagger specification in Yaml format and generate the interactive documentation, you can:

  • copy/paste the content of the Swagger Yaml file,
  • import a file from your local hard drive (File | Import file),
  • import a file from a URL (File | Import URL),

To generate the source code of the :

  • Go to http://0.0.0.0:82
  • copy/paste the content of the Swagger Yaml file,
  • or import a file from your local hard drive (File | Import file),
  • or import a file from a URL (File | Import URL).

Generate the server code

To generate the server source code, use: Generate Server | nodejs-server

Then decompress the generated source code:

mv ~/Downloads/nodejs-server-server-generated.zip .
unzip nodejs-server-server-generated.zip
rm nodejs-server-server-generated.zip

Display the contents of the ContactService.js file:

cat nodejs-server-server/service/ContactService.js

The content of this file is:

'use strict';
/**
 * Creates a new contact
 *
 * contact ContactCreateRequest The contact data
 * no response value expected for this operation
 **/
exports.createContact = function(contact) {
  return new Promise(function(resolve, reject) {
    resolve();
  });
}
/**
 * Gets the list of contacts
 * 
 *
 * returns ListContactsResponse
 **/
exports.getContacts = function() {
  return new Promise(function(resolve, reject) {
    var examples = {};
    examples['application/json'] = "";
    if (Object.keys(examples).length > 0) {
      resolve(examples[Object.keys(examples)[0]]);
    } else {
      resolve();
    }
  });
}

Then install the dependencies:

cd nodejs-server-server
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.
        ░░░░░░⸩ ⠹ build:multer: sill linkStuff multer@1.4.2 has /Users/bruKlease
> core-js@2.6.9 postinstall /Users/brunodelb/devops/notebooks/documentation/Swagger/nodejs-server-server/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.731s
found 5 vulnerabilities (2 low, 2 moderate, 1 high)
  run `npm audit fix` to fix them, or `npm audit` for details

Launch the NodeJS server:

node index

This command displays in the terminal:

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

Client code generation

To generate the client source code use : Generate Client | javascript

Then decompress the generated source code :

mv ~/Downloads/javascript-client-generated.zip .
unzip javascript-client-generated.zip
rm javascript-client-generated.zip

The file is unzipped :

Archive:  javascript-client-generated.zip
  inflating: javascript-client/src/index.js  
  inflating: javascript-client/src/model/ListContactsResponse.js  
  inflating: javascript-client/src/model/ContactResponse.js  
  inflating: javascript-client/src/model/ContactCreateRequest.js  
  inflating: javascript-client/src/api/ContactApi.js  
  inflating: javascript-client/src/ApiClient.js  
  inflating: javascript-client/mocha.opts  
  inflating: javascript-client/README.md  
  inflating: javascript-client/docs/ListContactsResponse.md  
  inflating: javascript-client/docs/ContactCreateRequest.md  
  inflating: javascript-client/docs/ContactResponse.md  
  inflating: javascript-client/docs/ContactApi.md  
  inflating: javascript-client/.swagger-codegen-ignore  
  inflating: javascript-client/.swagger-codegen/VERSION  
  inflating: javascript-client/.travis.yml  
  inflating: javascript-client/test/model/ContactResponse.spec.js  
  inflating: javascript-client/test/model/ListContactsResponse.spec.js  
  inflating: javascript-client/test/model/ContactCreateRequest.spec.js  
  inflating: javascript-client/test/api/ContactApi.spec.js  
  inflating: javascript-client/git_push.sh  
  inflating: javascript-client/package.json

Swagger UI

Swagger UI (https://github.com/swagger-api/swagger-ui) is an interactive tool for viewing and executing Swagger specification files. It allows you to publish interactive and attractive API documentation.

You can use android, bash, dar, go, java, jmeter, kotlin, php, python, swift4, or typescript-node.

Launch Swagger UI :

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

The result of the command is:

13d328f7157def0eae791631518cf1583fc29ee06476a538d9cd4fa84b63ae37

Go to http://0.0.0.0:83 to access the Swagger UI user interface.

Swagger Codegen

Swagger Codegen (https://github.com/swagger-api/swagger-codegen) allows to read specification files and generate the API client and server skeleton code in different languages.

For a list of supported languages :

docker run \
    --rm \
    -v $PWD:/local \
    swaggerapi/swagger-codegen-cli langs

Here is the result of the command:

Available languages: [ada, ada-server, akka-scala, android, apache2, apex, aspnetcore, bash, csharp, clojure, cwiki, cpprest, csharp-dotnet2, dart, elixir, elm, eiffel, erlang-client, erlang-server, finch, flash, python-flask, go, go-server, groovy, haskell-http-client, haskell, jmeter, jaxrs-cxf-client, jaxrs-cxf, java, inflector, jaxrs-cxf-cdi, jaxrs-spec, jaxrs, msf4j, java-pkmst, java-play-framework, jaxrs-resteasy-eap, jaxrs-resteasy, javascript, javascript-closure-angular, java-vertx, kotlin, lua, lumen, nancyfx, nodejs-server, objc, perl, php, powershell, pistache-server, python, qt5cpp, r, rails5, restbed, ruby, rust, rust-server, scala, scala-gatling, scala-lagom-server, scalatra, scalaz, php-silex, sinatra, slim, spring, dynamic-html, html2, html, swagger, swagger-yaml, swift4, swift3, swift, php-symfony, tizen, typescript-aurelia, typescript-angular, typescript-inversify, typescript-angularjs, typescript-fetch, typescript-jquery, typescript-node, undertow, ze-ph, kotlin-server]

To validate a specification:

docker run \
    --rm \
    -v $PWD:/app \
    swaggerapi/swagger-codegen-cli validate -i /app/swagger.yaml

This command returns the following result:

Validating spec file (/app/swagger.yaml)

PHP code generation

For PHP:

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

The output of the command is:

[main] INFO io.swagger.parser.Swagger20Parser - reading from /local/swagger.yaml
[main] WARN io.swagger.codegen.ignore.CodegenIgnoreProcessor - Output directory does not exist, or is inaccessible. No file (.swagger-codegen-ignore) will be evaluated.
[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/SwaggerClient-php/lib/Model/ContactCreateRequest.php
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/SwaggerClient-php/test/Model/ContactCreateRequestTest.php
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/SwaggerClient-php/docs/Model/ContactCreateRequest.md
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/SwaggerClient-php/lib/Model/ContactResponse.php
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/SwaggerClient-php/test/Model/ContactResponseTest.php
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/SwaggerClient-php/docs/Model/ContactResponse.md
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/SwaggerClient-php/lib/Model/ListContactsResponse.php
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/SwaggerClient-php/test/Model/ListContactsResponseTest.php
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/SwaggerClient-php/docs/Model/ListContactsResponse.md
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/SwaggerClient-php/lib/Api/ContactApi.php
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/SwaggerClient-php/test/Api/ContactApiTest.php
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/SwaggerClient-php/docs/Api/ContactApi.md
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/SwaggerClient-php/lib/ApiException.php
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/SwaggerClient-php/lib/Configuration.php
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/SwaggerClient-php/lib/ObjectSerializer.php
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/SwaggerClient-php/lib/Model/ModelInterface.php
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/SwaggerClient-php/lib/HeaderSelector.php
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/SwaggerClient-php/composer.json
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/SwaggerClient-php/README.md
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/SwaggerClient-php/phpunit.xml.dist
[main] INFO io.swagger.codegen.DefaultGenerator - writing file /local/out/SwaggerClient-php/.travis.yml
[main] INFO io.swagger.codegen.DefaultGenerator - writing file /local/out/SwaggerClient-php/.php_cs
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/SwaggerClient-php/git_push.sh
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/.swagger-codegen-ignore
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/.swagger-codegen/VERSION

Check that the code has been generated:

ls $PWD/out

This command shows that a directory has been created:

SwaggerClient-php

Let’s clean up our directory by deleting the subdirectory out.

rm -rf $PWD/out

Code generation for Python

For Python:

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

The output of this command is:

[main] INFO io.swagger.parser.Swagger20Parser - reading from /local/swagger.yaml
[main] WARN io.swagger.codegen.ignore.CodegenIgnoreProcessor - Output directory does not exist, or is inaccessible. No file (.swagger-codegen-ignore) will be evaluated.
[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/swagger_client/models/contact_create_request.py
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/test/test_contact_create_request.py
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/docs/ContactCreateRequest.md
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/swagger_client/models/contact_response.py
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/test/test_contact_response.py
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/docs/ContactResponse.md
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/swagger_client/models/list_contacts_response.py
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/test/test_list_contacts_response.py
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/docs/ListContactsResponse.md
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/swagger_client/api/contact_api.py
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/test/test_contact_api.py
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/docs/ContactApi.md
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/README.md
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/tox.ini
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/test-requirements.txt
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/requirements.txt
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/swagger_client/configuration.py
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/swagger_client/__init__.py
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/swagger_client/models/__init__.py
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/swagger_client/api/__init__.py
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/test/__init__.py
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/git_push.sh
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/.gitignore
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/.travis.yml
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/setup.py
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/swagger_client/api_client.py
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/swagger_client/rest.py
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/.swagger-codegen-ignore
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/.swagger-codegen/VERSION

Check that the files have been generated:

ls ./out

We can see that files have been generated:

README.md		requirements.txt	test
docs			setup.py		test-requirements.txt
git_push.sh		swagger_client		tox.ini

Let’s clean up our directory by deleting the out subdirectory.

rm -rf $PWD/out

Code generation for NodeJS

For NodeJS:

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

The output of the Docker container gives :

[main] INFO io.swagger.parser.Swagger20Parser - reading from /local/swagger.yaml
[main] WARN io.swagger.codegen.ignore.CodegenIgnoreProcessor - Output directory does not exist, or is inaccessible. No file (.swagger-codegen-ignore) will be evaluated.
[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/index.js
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/package.json
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/README.md
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/.swagger-codegen-ignore
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /local/out/.swagger-codegen/VERSION

Let’s see the generated files:

ls ./out

The Docker container did generate:

README.md	controllers	package.json	utils
api		index.js	service

Now you know how to use the different tools of the Swagger framework.

Comments

Your browser is out-of-date!

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

×