In this article, we will discuss creating and testing a Node/Express microservice using Swagger.
 

Technologies

  • node.js
  • express.js
  • swagger
  • supertest

 

Installing swagger

Before installing swagger for node.js, we need to make sure node and npm are installed.

Check the same using following commands :

node -v

npm -v

Now, we can install swagger using npm using :

npm install – g swagger

 

Create swagger project

We can create a swagger project using following command :

swagger project create hello-world

This command will ask you to choose the framework.. select “express” :


$ swagger project create hello-world
? Framework?
  connect
❯ express
  hapi
  restify
  sails

 
Here are some of the files we need to check :

swagger.yaml

The swagger.yaml contains documentation on the resource paths, routes and request/response schema definitions.
The below swagger.yaml contains details for any request for “/hello”.

 

hello_world.js

The swagger yaml contains the controller definition.


x-swagger-router-controller: hello_world

The hello_world.js controller will contain the business logic for handling the operation.

app.js

 

Running project

The project can be started using following command :

swagger project start


$ swagger project start
Starting: /services/hello-world/app.js...
  project started here: http://localhost:10010/
  project will restart on changes.
  to restart at any time, enter <code>rs

try this:
curl http://127.0.0.1:10010/hello?name=Scott

At this point, we can test the service using the curl or directly using the url:

http://127.0.0.1:10010/hello

“Hello, stranger!”

We can also pass a name as :

http://127.0.0.1:10010/hello?name=John

“Hello, John!”
 

Swagger UI

swagger project edit

The project can be tested using swagger UI using following command :

swagger project edit


$ swagger project edit
Starting Swagger Editor.
Opening browser to: http://127.0.0.1:51396/#/edit
Do not terminate this process or close this window until finished editing.

 

Testing project

The swagger project would automatically create the supertest test script in test folder.

 
The project can be tested using :

swagger project test


$ swagger project test
Running tests in: /services/hello-world/test...

try this:
curl http://127.0.0.1:10010/hello?name=Scott
  controllers
    hello_world
      GET /hello
        ✓ should return a default string (96ms)
        ✓ should accept a name parameter

  2 passing (2s)

done

 

© 2021, www.topjavatutorial.com. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags