search
HomeWeb Front-endJS TutorialCreating RESTful APIs with Express 4

Creating RESTful APIs with Express 4

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:

Creating RESTful APIs with Express 4

Directory Structure

We will use the following directory structure in our app:

Creating RESTful APIs with Express 4

Here are some points about the above directory structure:

  1. The bin/www.js is used to bootstrap our app.
  2. The models directory stores our mongoose models. For this app we will have just one file called movie.js.
  3. The routes directory will store all the Express routes.
  4. 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:

  1. Express
  2. Body parser
  3. 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:

<span>{
</span>  <span>"name": "Movie CRUD API",
</span>  <span>"version": "0.0.1",
</span>  <span>"private": true,
</span>  <span>"scripts": {
</span>    <span>"start": "node ./bin/www"
</span>  <span>},
</span>  <span>"main":"./bin/www",
</span>  <span>"engines": {
</span>     <span>"node": "0.10.x"
</span>   <span>},
</span>  <span>"dependencies": {
</span>    <span>"express": "~4.2.0",
</span>    <span>"body-parser": "~1.0.0",
</span>    <span>"mongoose": "~3.8.11"
</span>  <span>}
</span><span>}</span>

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.

<span>var mongoose=require('mongoose');
</span><span>var Schema=mongoose.<span>Schema</span>;
</span>
<span>var movieSchema = new Schema({
</span>  <span>title: String,
</span>  <span>releaseYear: String,
</span>  <span>director: String,
</span>  <span>genre: String
</span><span>});
</span>
module<span>.exports = mongoose.model('Movie', movieSchema);</span>

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:

<span>var Movie = require('../models/movie');
</span><span>var express = require('express');
</span><span>var router = express.<span>Router</span>();</span>

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<span>.route('/movies').get(function(req<span>, res</span>) {
</span>  <span>Movie.find(function(err<span>, movies</span>) {
</span>    <span>if (err) {
</span>      <span>return res.send(err);
</span>    <span>}
</span>
    res<span>.json(movies);
</span>  <span>});
</span><span>});</span>

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<span>.route('/movies').post(function(req<span>, res</span>) {
</span>  <span>var movie = new Movie(req.body);
</span>
  movie<span>.save(function(err) {
</span>    <span>if (err) {
</span>      <span>return res.send(err);
</span>    <span>}
</span>
    res<span>.send({ message: 'Movie Added' });
</span>  <span>});
</span><span>});</span>

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<span>.route('/movies')
</span>  <span>.get(function(req<span>, res</span>) {
</span>    <span>Movie.find(function(err<span>, movies</span>) {
</span>      <span>if (err) {
</span>        <span>return res.send(err);
</span>      <span>}
</span>
      res<span>.json(movies);
</span>    <span>});
</span>  <span>})
</span>  <span>.post(function(req<span>, res</span>) {
</span>    <span>var movie = new Movie(req.body);
</span>
    movie<span>.save(function(err) {
</span>      <span>if (err) {
</span>        <span>return res.send(err);
</span>      <span>}
</span>
      res<span>.send({ message: 'Movie Added' });
</span>    <span>});
</span>  <span>});</span>

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.

<span>{
</span>  <span>"name": "Movie CRUD API",
</span>  <span>"version": "0.0.1",
</span>  <span>"private": true,
</span>  <span>"scripts": {
</span>    <span>"start": "node ./bin/www"
</span>  <span>},
</span>  <span>"main":"./bin/www",
</span>  <span>"engines": {
</span>     <span>"node": "0.10.x"
</span>   <span>},
</span>  <span>"dependencies": {
</span>    <span>"express": "~4.2.0",
</span>    <span>"body-parser": "~1.0.0",
</span>    <span>"mongoose": "~3.8.11"
</span>  <span>}
</span><span>}</span>

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.

<span>var mongoose=require('mongoose');
</span><span>var Schema=mongoose.<span>Schema</span>;
</span>
<span>var movieSchema = new Schema({
</span>  <span>title: String,
</span>  <span>releaseYear: String,
</span>  <span>director: String,
</span>  <span>genre: String
</span><span>});
</span>
module<span>.exports = mongoose.model('Movie', movieSchema);</span>

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()).

<span>var Movie = require('../models/movie');
</span><span>var express = require('express');
</span><span>var router = express.<span>Router</span>();</span>

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:

router<span>.route('/movies').get(function(req<span>, res</span>) {
</span>  <span>Movie.find(function(err<span>, movies</span>) {
</span>    <span>if (err) {
</span>      <span>return res.send(err);
</span>    <span>}
</span>
    res<span>.json(movies);
</span>  <span>});
</span><span>});</span>

Configuring the App

All our configurations go into app.js. We start by requiring the necessary modules:

router<span>.route('/movies').post(function(req<span>, res</span>) {
</span>  <span>var movie = new Movie(req.body);
</span>
  movie<span>.save(function(err) {
</span>    <span>if (err) {
</span>      <span>return res.send(err);
</span>    <span>}
</span>
    res<span>.send({ message: 'Movie Added' });
</span>  <span>});
</span><span>});</span>

The next step is connecting to MongoDB via Mongoose:

router<span>.route('/movies')
</span>  <span>.get(function(req<span>, res</span>) {
</span>    <span>Movie.find(function(err<span>, movies</span>) {
</span>      <span>if (err) {
</span>        <span>return res.send(err);
</span>      <span>}
</span>
      res<span>.json(movies);
</span>    <span>});
</span>  <span>})
</span>  <span>.post(function(req<span>, res</span>) {
</span>    <span>var movie = new Movie(req.body);
</span>
    movie<span>.save(function(err) {
</span>      <span>if (err) {
</span>        <span>return res.send(err);
</span>      <span>}
</span>
      res<span>.send({ message: 'Movie Added' });
</span>    <span>});
</span>  <span>});</span>

Finally, we configure the middleware:

router<span>.route('/movies/:id').put(function(req<span>,res</span>){
</span>  <span>Movie.findOne({ _id: req.params.id }, function(err<span>, movie</span>) {
</span>    <span>if (err) {
</span>      <span>return res.send(err);
</span>    <span>}
</span>
    <span>for (prop in req.body) {
</span>      movie<span>[prop] = req.body[prop];
</span>    <span>}
</span>
    <span>// save the movie
</span>    movie<span>.save(function(err) {
</span>      <span>if (err) {
</span>        <span>return res.send(err);
</span>      <span>}
</span>
      res<span>.json({ message: 'Movie updated!' });
</span>    <span>});
</span>  <span>});
</span><span>});</span>

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:

router<span>.route('/movies/:id').get(function(req<span>, res</span>) {
</span>  <span>Movie.findOne({ _id: req.params.id}, function(err<span>, movie</span>) {
</span>    <span>if (err) {
</span>      <span>return res.send(err);
</span>    <span>}
</span>
    res<span>.json(movie);
</span>  <span>});
</span><span>});</span>

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.

Creating RESTful APIs with Express 4

Creating RESTful APIs with Express 4

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!’.

The above is the detailed content of Creating RESTful APIs with Express 4. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor