EJB & Express
EJB & Express
RESTful URIs and methods provide us with almost all information we need to process a
request. The table given below summarizes how the various verbs should be used and how
URIs should be named. We will be creating a movies API towards the end; let us now
discuss how it will be structured.
Safe,
GET /movies Gets the list of all movies and their details
cachable
Safe,
GET /movies/1234 Gets the details of Movie id 1234
cachable
Let us now create this API in Express. We will be using JSON as our transport data format
as it is easy to work with in JavaScript and has other benefits. Replace your index.js file
with the movies.js file as in the following program.
index.js
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(upload.array());
app.listen(3000);
Now that we have our application set up, let us concentrate on creating the API.
Start by setting up the movies.js file. We are not using a database to store the movies but
are storing them in memory; so every time the server restarts, the movies added by us
will vanish. This can easily be mimicked using a database or a file (using node fs module).
Once you import Express then, create a Router and export it using module.exports −
GET routes
Let us define the GET route for getting all the movies −
});
To test out if this is working fine, run your app, then open your terminal and enter −
[{"id":101,"name":"Fight Club","year":1999,"rating":8.1},
{"id":102,"name":"Inception","year":2010,"rating":8.7},
{"id":103,"name":"The Dark Knight","year":2008,"rating":9},
{"id":104,"name":"12 Angry Men","year":1957,"rating":8.9}]
We have a route to get all the movies. Let us now create a route to get a specific movie by
its id.
This will get us the movies according to the id that we provided. To check the output, use
the following command in your terminal −
{"id":101,"name":"Fight Club","year":1999,"rating":8.1}
Page 4 of 9
If you visit an invalid route, it will produce a cannot GET error while if you visit a valid
route with an id that doesn’t exist, it will produce a 404 error.
We are done with the GET routes, let us now move on to the POST route.
Explore our latest online courses and learn new skills at your own pace. Enroll and
become a certified expert to boost your career.
POST route
Use the following route to handle the POSTed data −
res.status(400);
res.json({message: "Bad Request"});
} else {
var newId = movies[movies.length-1].id+1;
movies.push({
id: newId,
name: req.body.name,
year: req.body.year,
rating: req.body.rating
});
res.json({message: "New movie created.", location: "/movies/" + newId
}
});
This will create a new movie and store it in the movies variable. To check this route, enter
the following code in your terminal −
To test if this was added to the movies object, Run the get request for /movies/105
again. The following response will be displayed −
Page 5 of 9
{"id":105,"name":"Toy story","year":"1995","rating":"8.5"}
PUT route
The PUT route is almost the same as the POST route. We will be specifying the id for the
object that'll be updated/created. Create the route in the following way.
res.status(400);
res.json({message: "Bad Request"});
} else {
//Gets us the index of movie with given id.
var updateIndex = movies.map(function(movie){
return movie.id;
}).indexOf(parseInt(req.params.id));
}
});
This route will perform the function specified in the above table. It will update the object
with new details if it exists. If it doesn't exist, it will create a new object. To check the
route, use the following curl command. This will update an existing movie. To create a new
Movie, just change the id to a non-existing id.
Response
DELETE route
Use the following code to create a delete route. −
Check the route in the same way as we checked the other routes. On successful
deletion(for example id 105), you will get the following output −
var movies = [
{id: 101, name: "Fight Club", year: 1999, rating: 8.1},
{id: 102, name: "Inception", year: 2010, rating: 8.7},
{id: 103, name: "The Dark Knight", year: 2008, rating: 9},
{id: 104, name: "12 Angry Men", year: 1957, rating: 8.9}
];
router.get('/:id([0-9]{3,})', function(req, res){
var currMovie = movies.filter(function(movie){
if(movie.id == req.params.id){
return true;
}
});
if(currMovie.length == 1){
res.json(currMovie[0])
} else {
res.status(404); //Set status to 404 as movie was not found
res.json({message: "Not Found"});
}
});
router.post('/', function(req, res){
//Check if all fields are provided and are valid:
if(!req.body.name ||
!req.body.year.toString().match(/^[0-9]{4}$/g) ||
!req.body.rating.toString().match(/^[0-9]\.[0-9]$/g)){
res.status(400);
res.json({message: "Bad Request"});
} else {
var newId = movies[movies.length-1].id+1;
movies.push({
id: newId,
name: req.body.name,
year: req.body.year,
rating: req.body.rating
});
res.json({message: "New movie created.", location: "/movies/" + newId
}
});
res.status(400);
res.json({message: "Bad Request"});
} else {
//Gets us the index of movie with given id.
var updateIndex = movies.map(function(movie){
return movie.id;
}).indexOf(parseInt(req.params.id));
This completes our REST API. Now you can create much more complex applications using
this simple architectural style and Express.