Initialize the Project
> mkdir restTest
> cd restTest
> npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (resttest)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to /Users/john.mehan/dev/node/restTest/package.json:
{
"name": "resttest",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Is this ok? (yes)
>
This will have created your package.json file.
Add Packages
Let's install express and nodmon, express will be used to create the server while nodmon will help us to keep track of changes to our application by watching changed files and automatically restart the server.
> npm install --save-dev nodemon > npm install express --save
Code
> vi server.js
var express = require('express'),
app = express(),
port = process.env.PORT || 3000
bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var routes = require('./routes'); //importing route
routes(app); //register the route
app.listen(port);
console.log('todo list RESTful API server started on: ' + port);
vi routes.js
'use strict';
module.exports = function(app) {
var controller = require('./controller');
// Routes
app.route('/tasks')
.get(controller.list_all_tasks)
};
> vi controller.js
'use strict';
exports.list_all_tasks = function(req, res) {
res.send("hi");
};
Run it:
> npm run start
Navigate to http://localhost:3000/tasks
References
| Reference | URL |
|---|---|
Build Node.js RESTful APIs in 10 Minutes | https://www.codementor.io/@olatundegaruba/nodejs-restful-apis-in-10-minutes-q0sgsfhbd |