Reading:
Publish REST API with a Node JS app

Publish REST API with a Node JS app

Metamug
Publish REST API with a Node JS app

In this article we shall use Metamug API Console to publish an API endpoint which forwards the API request to a Node JS application.

Start Node Server

Download node, create a new nodejs project and install express, bodyparser.

Express JS server

const express = require('express')
const bodyParser = require('body-parser')

const app = express()

app.use(bodyParser.json())

app.get('/addfive/:int', (req,res)=> {
    const integer = req.params.int
    res.send(\`Sum:::${parseInt(integer) + 5}\`)
})

app.listen(5000, () => console.log(\`App Running on port 5000 ::::\`))

Create Express Application

Import Express and create a new express application:

//Import Express
const express = require('express');

//Create Express App
const app = express();

Body Parser

Body parser is a package that parses incoming request stream and makes in available under the req.body property.

//Import body-parser
const bodyParser = require('body-parser');

//Use body-parser middleware
app.use(bodyParser.json());  // parse application/json

It is important to note that body parser middleware should be used before the actual route handlers.

Route Handler

app.get('/addfive/:int', (req,res)=> {
    const integer = req.params.int
    res.send(\`Sum:::${parseInt(integer) + 5}\`)
});

I have defined a simple route handler which will handle GET request at “{base_url}/addfive/{integer_user_input}” .

Every time a request is made, integer 5 is added to the incoming user input (integer that will come after /addfive/ , example: /addfive/5 will return 10 as sum) and output is set as response in JSON format.

Running The Application

app.listen(5000, () => console.log(\`App Running on port 5000 ::::\`))

This is how we run an express application on a specific port.

Setting up API Console

Create a backend in Metamug API console and create a resource file named "nodeapi" and paste the following XML inside it.

<Resource xmlns="http://xml.metamug.net/resource/1.0" v="1.0">
  <Request method="GET">
     <XRequest id="nodeapp" url="http://localhost:5000/addfive/14" method="GET" output="true">              
     </XRequest>
  </Request>
</Resource>

The above XML resource represents an XRequest from console to the node application running on port 5000. We specify output=”true” to see the output in JSON format.

Output

Now we make a GET request to the API console endpoint {baseUrl}/v1.0/nodeapi to receive the following response

{
  "nodeapp": {
    "sum": 19
  }
}

In this manner we have used API console endpoint to make request to another application. Publishing an API console endpoint enables you to perform API management and opens up possibilities for integrations with other API based services.



Comments

Post a comment
Icon For Arrow-up