With the release of Express 4 it has gotten even easier to create RESTful APIs. If you are creating a Single Page App you will definitely need a RESTful web service which supports CRUD operations. My last tutorial focussed on creating a Single Page CRUD app with Angular’s $resource. This tutorial explains how to design the backend API for such a CRUD app using Express 4.
Just note that a lot has been changed since Express 3. This tutorial doesn’t explain how to upgrade your app from Express 3 to Express 4. Rather it will cover how to create the API with Express 4 directly. So, let’s get started.
Key Takeaways
- Express 4 simplifies the creation of RESTful APIs, making it easier to design backend APIs for CRUD applications.
- Express 4 requires body-parser to be downloaded separately as it’s no longer part of the Express core. This module is used to parse incoming request bodies, allowing access to the body of a POST request via req.body.
- The Express 4 method express.Router() creates a new router instance that can define middlewares and routes. This router instance can then be used in the main app just like any other middleware by calling app.use().
- Express 4 supports standard HTTP methods, such as GET, POST, PUT, and DELETE, to perform CRUD operations on a database, in this case, a movie database. This is done through creating routes that handle these HTTP requests.
Creating the API for the Movie App
Our app will be a simple movie database which supports basic CRUD operations. We will use Express 4 as the web framework and MongooseJS as the object modeling tool. To store the movie entries we will use MongoDB.
Before going further let’s take a look at what the API will look like:
Directory Structure
We will use the following directory structure in our app:
Here are some points about the above directory structure:
- The
bin/www.js
is used to bootstrap our app. - The
models
directory stores our mongoose models. For this app we will have just one file calledmovie.js
. - The
routes
directory will store all the Express routes. - The
app.js
holds the configurations for our Express app.
Finally, node_modules
and package.json
are the usual components of a Node.js app.
Obtaining Necessary Dependencies
To create the API we will use the following modules:
- Express
- Body parser
- Mongoose
Note – body-parser
is not a part of the Express core anymore. You need to download the module separately. So, we have listed it in the package.json
.
To obtain these packages we will list them as dependencies in our package.json
. Here is our package.json
file:
{
"name": "Movie CRUD API",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"main":"./bin/www",
"engines": {
"node": "0.10.x"
},
"dependencies": {
"express": "~4.2.0",
"body-parser": "~1.0.0",
"mongoose": "~3.8.11"
}
}
Just run npm install
and all the dependencies will be downloaded and placed under the node_modules
directory.
Creating the Model
Since we are building an API for a movie database we will create a Movie
model. Create a file named movie.js
and put it in the models
directory. The contents of this file, shown below, create a Mongoose model.
var mongoose=require('mongoose');
var Schema=mongoose.Schema;
var movieSchema = new Schema({
title: String,
releaseYear: String,
director: String,
genre: String
});
module.exports = mongoose.model('Movie', movieSchema);
In the previous snippet we create a new model, Movie
. Each movie has four properties associated with it – title, release year, director, and genre. Finally, we put the model in the module.exports
so that we can access it from the outside.
Creating the Routes
All of our routes go in routes/movies.js
. To start, add the following to your movies.js
file:
var Movie = require('../models/movie');
var express = require('express');
var router = express.Router();
Express 4 has a new method called express.Router()
which gives us a new router
instance. It can be used to define middlewares and routes. The interesting point about Express router
is that it’s just like a mini application. You can define middlewares and routes using this router and then just use it in your main app just like any other middleware by calling app.use()
.
Getting All the Movies
When users send a GET
request to /api/movies
, we should send them a response containing all the movies. Here is the snippet that creates a route for this.
router.route('/movies').get(function(req, res) {
Movie.find(function(err, movies) {
if (err) {
return res.send(err);
}
res.json(movies);
});
});
router.route()
returns a single route instance which can be used to configure one or more HTTP verbs. Here, we want to support a GET
request. So, we call get()
and pass a callback which will be called when a request arrives. Inside the callback we retrieve all the movies using Mongoose and send them back to the client as JSON.
Creating a New Movie
Our API should create a new movie in the database when a POST
request is made to /api/movies
. A JSON string must be sent as the request body. We will use the same route, /movies
, but use the method post()
instead of get()
.
Here is the code:
router.route('/movies').post(function(req, res) {
var movie = new Movie(req.body);
movie.save(function(err) {
if (err) {
return res.send(err);
}
res.send({ message: 'Movie Added' });
});
});
Here, we create a new Movie
instance from the request body. This is where body-parser
is used. Then we just save the new movie and send a response indicating that the operation is successful.
Note that the methods get()
, post()
, etc. return the same route
instance. So, you can in fact chain the previous two calls as shown below.
router.route('/movies')
.get(function(req, res) {
Movie.find(function(err, movies) {
if (err) {
return res.send(err);
}
res.json(movies);
});
})
.post(function(req, res) {
var movie = new Movie(req.body);
movie.save(function(err) {
if (err) {
return res.send(err);
}
res.send({ message: 'Movie Added' });
});
});
Updating a Movie
If users want to update a movie, they need to send a PUT
request to /api/movies/:id
with a JSON string as the request body. We use the named parameter :id
to access an existing movie. As we are using MongoDB, all of our movies have a unique identifier called _id
. So, we just need to retrieve the parameter :id
and use it to find a particular movie. The code to do this is shown below.
router.route('/movies/:id').put(function(req,res){
Movie.findOne({ _id: req.params.id }, function(err, movie) {
if (err) {
return res.send(err);
}
for (prop in req.body) {
movie[prop] = req.body[prop];
}
// save the movie
movie.save(function(err) {
if (err) {
return res.send(err);
}
res.json({ message: 'Movie updated!' });
});
});
});
Here, we create a new route /movies/:id
and use the method put()
. The invokation of Movie.findOne({ _id: req.params.id })
is used to find the movie whose id
is passed in the URL. Once we have the movie
instance, we update it based on the JSON passed in the request body. Finally, we save this movie
and send a response to the client.
Retrieving a Movie
To read a single movie, users need to send a GET
request to the route /api/movies/:id
. We will use the same route as above, but use get()
this time.
router.route('/movies/:id').get(function(req, res) {
Movie.findOne({ _id: req.params.id}, function(err, movie) {
if (err) {
return res.send(err);
}
res.json(movie);
});
});
The rest of the code is pretty straightforward. We retrieve a movie based on the passed id
and send it to the user.
Deleting a Movie
To delete a movie, users should send a DELETE
request to /api/movies/:id
. Again, the route is the same as above, but the method is different (i.e. delete()
).
router.route('/movies/:id').delete(function(req, res) {
Movie.remove({
_id: req.params.id
}, function(err, movie) {
if (err) {
return res.send(err);
}
res.json({ message: 'Successfully deleted' });
});
});
The method Movie.remove()
deletes a movie from the database, and we send a message to the user indicating success.
Now we are all set. But wait! We need to put the router
instance in the module.exports
so that we can use it in our app as a middlewaree. So, this is the last line in the file movies.js
:
module.exports = router;
Configuring the App
All our configurations go into app.js
. We start by requiring the necessary modules:
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var movies = require('./routes/movies'); //routes are defined here
var app = express(); //Create the Express app
The next step is connecting to MongoDB via Mongoose:
//connect to our database
//Ideally you will obtain DB details from a config file
var dbName = 'movieDB';
var connectionString = 'mongodb://localhost:27017/' + dbName;
mongoose.connect(connectionString);
Finally, we configure the middleware:
//configure body-parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use('/api', movies); //This is our route middleware
module.exports = app;
As you can see I have used the router
just like any other middleware. I passed /api
as the first argument to app.use()
so that the route middleware is mapped to /api
. So, in the end our API URLs become:
/api/movies
/api/movies/:id
Bootstrapping
The following code goes into bin/www.js
, which bootstraps our app:
var app = require('../app'); //Require our app
app.set('port', process.env.PORT || 8000);
var server = app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + server.address().port);
});
By running node bin/www.js
, your API should be up!
Testing the API
Now that we have created the API we should test it to make sure everything works as expected. You can use Postman, a Chrome extension, to test all of your endpoints. Here are a few screenshots that show POST
and GET
requests being tested in Postman.
Conclusion
This was a basic overview of how you can create RESTful APIs easily with Node and Express. If you want to dig deeper into Express be sure to check out their docs. If you want to add or ask something please feel free to comment.
The source code for the app is available for download on GitHub.
Frequently Asked Questions (FAQs) about Creating RESTful APIs with Express 4
What is the difference between RESTful APIs and other types of APIs?
RESTful APIs, or Representational State Transfer APIs, are a type of API that adhere to the principles of REST architectural style. They are stateless, meaning each request from a client to a server must contain all the information needed to understand and process the request. This is different from other types of APIs, such as SOAP, which can maintain state between requests. RESTful APIs also use standard HTTP methods, like GET, POST, PUT, DELETE, making them easy to understand and use.
How do I create a basic route in Express 4?
In Express 4, you can create a basic route using the app.get()
method. This method takes two arguments: the path and a callback function. The callback function is executed whenever a GET request is made to the specified path. Here’s an example:app.get('/', function(req, res) {
res.send('Hello World!');
});
In this example, when a GET request is made to the root path (‘/’), the server will respond with ‘Hello World!’.
How do I handle POST requests in Express 4?
To handle POST requests in Express 4, you can use the app.post()
method. This method works similarly to app.get()
, but it is used for POST requests instead of GET requests. Here’s an example:app.post('/', function(req, res) {
res.send('POST request received');
});
In this example, when a POST request is made to the root path (‘/’), the server will respond with ‘POST request received’.
What is middleware in Express 4 and how do I use it?
Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware. Middleware functions can perform the following tasks: execute any code, make changes to the request and the response objects, end the request-response cycle, call the next middleware in the stack.
How do I handle errors in Express 4?
Express 4 provides a built-in error handler, which takes care of any errors that might occur in the app. If you need to handle specific errors, you can create your own error-handling middleware function. Here’s an example:app.use(function(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
In this example, if an error occurs in the app, it will be logged to the console and the server will respond with a status code of 500 and a message of ‘Something broke!’.
How do I use parameters in Express 4 routes?
You can use route parameters to capture dynamic values in the URL. These values can then be used by your route handlers. Here’s an example:app.get('/users/:userId', function(req, res) {
res.send('User ID is: ' + req.params.userId);
});
In this example, when a GET request is made to ‘/users/123’, the server will respond with ‘User ID is: 123’.
How do I serve static files in Express 4?
Express 4 provides a built-in middleware function, express.static()
, for serving static files. You can use it to serve files from a directory on your server. Here’s an example:app.use(express.static('public'));
In this example, files in the ‘public’ directory can be accessed directly from the root URL (‘/’).
How do I use the body-parser middleware in Express 4?
The body-parser middleware is used to parse incoming request bodies. This allows you to access the body of a POST request via req.body
. Here’s an example:var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
In this example, the body-parser middleware is configured to parse JSON and URL-encoded bodies.
How do I handle 404 errors in Express 4?
You can handle 404 errors by adding a middleware function at the end of your middleware stack. This function will be executed if no other route handlers or middleware functions have handled the request. Here’s an example:app.use(function(req, res, next) {
res.status(404).send('Sorry, we cannot find that!');
});
In this example, if a request is made to a path that doesn’t exist, the server will respond with a status code of 404 and a message of ‘Sorry, we cannot find that!’.
How do I use Express Router in Express 4?
Express Router is a mini-application in Express 4 that allows you to organize your routes in a modular way. You can create a new router with express.Router()
, add middleware and routes to it, and then use it in your app with app.use()
. Here’s an example:var router = express.Router();
router.get('/', function(req, res) {
res.send('Hello from the router!');
});
app.use('/router', router);
In this example, when a GET request is made to ‘/router’, the server will respond with ‘Hello from the router!’.
Sandeep is the Co-Founder of Hashnode. He loves startups and web technologies.