How to do it...

We're going to create a service that adds two numbers together.

A service is simply a Node process, so let's go ahead and create an adderservice folder inside our micro directory, initialize our new folder as a package, and create a service.js file:

 $ mkdir adderservice
$ cd adderservice
$ npm init -y
$ touch service.js

This will create a fresh package.json for us. Next let's add in the restify module for our service with the following command:

npm install restify --save --no-optional

This will install the restify module and also add the dependency to package.json

--no-optional
By default, restify installs DTrace probes, this can be disabled during install with the         --no-optional flag. While DTrace is great not all systems support it which is why we have chosen to disable it in this example. We can find out more about DTrace at http://dtrace.org/blogs/about/.

 

Now it's time to actually write our service. Using our favorite editor, let's add the following code to the service.js file:

const restify = require('restify')

function respond (req, res, next) {
const result = (parseInt(req.params.first, 10) +
parseInt(req.params.second, 10)).toString()
res.send(result)
next()
}

const server = restify.createServer()
server.get('/add/:first/:second', respond)

server.listen(8080, () => {
console.log('%s listening at %s', server.name, server.url)
})

To see if everything is working we'll start the service.js file:

$ node service.js 

Which should give the following output:

restify listening at http://[::]:8080 
Let's test our service using curl. 

Now we can open a fresh terminal and type the following:

$ curl http://localhost:8080/add/1/2 

The service should respond with the answer: 3.

We have just built our first RESTful microservice.

curl
curl is a command line HTTP client program that works much like a web browser. If we don't have curl available on our system we can test the service by putting the URL into our web browser.