Saturday, 8 November 2014

Creating a simple REST API with Node Express

Install dependencies

npm install express
npm install body-parser
npm install morgan

Create: server.js

var express = require('express');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var films = require('./film-data.json');
var app = express();
app.use(bodyParser.json());
// logs incoming requests
app.use(morgan('combined'));
var router = express.Router();
router.get('/films', function(req, res) {
res.json(films);
});
router.get('/films/:id', function(req, res) {
if(films.length <= req.params.id || req.params.id < 0) {
res.statusCode = 404;
return res.send('Error 404: No film found');
}
var film = films[req.params.id];
res.json(film);
});
router.post('/films', function(req, res) {
if(!req.body.hasOwnProperty('title')) {
res.statusCode = 400;
return res.send('Error 400: Post syntax incorrect.');
}
var newFilm = {
id: films.length,
title: req.body.title
};
films.push(newFilm);
res.json(true);
});
router.delete('/films/:id', function(req, res) {
if(films.length <= req.params.id) {
res.statusCode = 404;
return res.send('Error 404: No film found');
}
films.splice(req.params.id, 1);
res.json(true);
});
app.use('/api', router);
console.log('Open a browser: http://localhost:3412/api/films');
app.listen(process.env.PORT || 3412);

Create film-data.json

[
{
"id": 0,
"title": "Interstellar",
"imageUrl": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX214_AL_.jpg",
"releaseDate": "2014-11-07",
"rating": "PG-13",
"length": 169,
"stars": [
{
"name": "Matthew McConaughey"
},
{
"name": "Anne Hathaway"
},
{
"name": "Jessica ChastainNothing"
}
]
},
{
"id": 1,
"title": "Fury",
"imageUrl": "http://ia.media-imdb.com/images/M/MV5BMjA4MDU0NTUyN15BMl5BanBnXkFtZTgwMzQxMzY4MjE@._V1_SX214_AL_.jpg",
"releaseDate": "2014-10-17",
"rating": "R",
"length": 134,
"stars": [
{
"name": "Brad Pitt"
},
{
"name": "Shia LaBeouf"
},
{
"name": "Logan Lerman"
}
]
},
{
"id": 2,
"title": "The Theory of Everything",
"imageUrl": "http://ia.media-imdb.com/images/M/MV5BMTAwMTU4MDA3NDNeQTJeQWpwZ15BbWU4MDk4NTMxNTIx._V1_SX214_AL_.jpg",
"releaseDate": "2015-01-16",
"rating": "PG-13",
"length": 123,
"stars": [
{
"name": "Eddie Redmayne"
},
{
"name": "Felicity Jones"
},
{
"name": "Tom Prior"
}
]
}
]
view raw film-data.json hosted with ❤ by GitHub

Start the server

node server.js

image

image

image

image

You can download and run the full source without the need to install any dependencies:  https://github.com/stevenh77/simple-rest-express-server

No comments:

Post a Comment