William Oliveira

Programming stuff

Simple REST API Using Express Node.js Framework

| Comments

Hello, folks!

Recently I’ve been working a lot with Node.js, specifically with Express, so I decided to write this blogpost to help anyone who wants to start out using it, and show how to implement a basic REST API using the platform.

I’m gonna list what you’ll need to follow up this article:

You can either use the local express or install it globally npm install -g express.

Let’s create our app express my-app.

Now, the package.json listing the dependencies of the project we’ll be working on:

package.json
1
2
3
4
5
6
7
8
{
  "name": "application-name",
  "version": "0.0.1",
  "dependencies": {
    "express": "*",
    "mongoose": "*"
  }
}

Go to the app directory and install the dependencies:

1
2
cd my-app
npm install

Great! If everything went well, you have your express app created!

Try running it just to see how it looks like:

1
2
node app
open http://localhost:3000

Now let’s get to the API.

I’ll be creating a simple User API, where you can create, read, update, delete and list the Users of your application.

The User attributes will be:

1
2
3
4
name: String,
surname: String,
email: String,
password: String

The REST API will look like this at the end:

1
2
3
4
5
GET /users - list all the users
GET /users/:id - read the user by id
POST /users - create a new user
PUT /users/:id - update the user by id
DELETE /users/:id - delete the user by id

Let’s create our first model! On the my-app directory, create a new dir called models and inside of it, a file called user.js:

1
2
3
mkdir models
cd models
touch user.js

Open the user.js file and create our model:

1
2
3
4
5
6
7
8
9
10
11
12
var mongoose = require('mongoose')
  , Schema = mongoose.Schema;

var User = new Schema({
    name:  String,
    surname: String,
    username: String,
    email: String,
    password: String
});

module.exports = mongoose.model('User', User);

Yay! We created our User model. Now, we have to implement the controller.

Go to the app root directory, and create a new dir called controllers, and a file user.js.

1
2
3
mkdir controllers
cd controllers
touch user.js

Implement the controller methods:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
var User = require('../models/user.js');

exports.create = function(req, res) {
  User.findOne({ username: req.body.username }, function(err, user) {
    if(user != null) {
      res.send('user exists');
      return false;
    }

    new User({
      name: req.body.name,
      surname: req.body.surname,
      username: req.body.username,
      email: req.body.email,
      password: req.body.password
    }).save();

    res.send('success');
  });
}

exports.read = function(req, res) {
  User.findOne({ _id: req.params.id }, function(err, user) {
    res.send(user);
  });
}

exports.update = function(req, res) {
  User.update({ _id: req.params.id }, {
    $set: {
      name: req.body.name,
      surname: req.body.surname,
      email: req.body.email,
      password: req.body.password
    }
  }).exec();

  return res.send('success');
}

exports.delete = function(req, res) {
  return User.findById(req.body.id, function(err, user) {
    return user.remove(function (err) {
      if (!err) {
        return res.send('removed');
      } else {
        return res.send(err);
      }
    });
  });
}

exports.list = function(req, res) {
  User.find(function(err, users) {
    res.send(users);
  });
}

I’m not going to explain the code above, because it’s not the aim of this article. If you don’t know what’s going on there, I recommend you study a little more about Node.JS and Express, plus, read some Mongoose docs (if you’re already familiar with MongoDB or any other NoSQL database).

Well, we now have implemented our model and controller. It’s time to manipulate some data.

Let’s create our routes!

Open the app.js file of your project, and include the Mongoose lib and it’s connector, right after creating the app:

1
2
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/users');

Now include the controller, on the top of the app.js:

1
var user = require('./controllers/user');

Great! We can now define our routes:

1
2
3
4
5
6
// user api
app.get('/users', user.list);
app.get('/users/:id', user.read);
app.post('/users', user.create);
app.put('/users/:id', user.update);
app.delete('/users/:id', user.delete);

Well done! Here’s our simple REST API example.

You can now insert some data, list, update, delete…

For now, it’s all handled on the API, but in the next articles, I will be explaining how to implement views to manipulate our data.

The source code of this article is on GitHub. Go there and take a look.

If you have any questions or there’s some wrong code or spelling, please send me an e-mail or comment below!

Stay in touch! Thanks!

Migrating to Octopress

| Comments

Welcome!

Today, I’ve started using Octopress, and I’m really happy with it.

If you liked, and got interested about Octopress, I’d recommend going through the docs to get started and make your own personal page/blog, using gh-pages.

Here’s the link: Deploying to Github Pages.

I’ll be posting about JavaScript, Node.JS, Ember.js, AngularJS, NoSQL, Python, and anything else I’m studying/working with.

Hope you enjoy, thanks!