Once you learn a little bit of Node.js you find that modules make life much easier. One of the most popular and useful is Express. It carries a lot of similarities to the Ruby framework, Sinatra. This makes it a great tool for building REST APIs. This article will teach how to use Express and build a basic REST API.
Installing Express npm Module
The first thing we need to do is install the Express module. This can be done a couple different ways.
The first method is updating your package.json file (or creating one) with the dependency for Express. The updates to the package.json will look similar to below.
{
"name": "first-express-app",
"description": "a fine piece of express art",
"version": "0.0.1",
"dependencies": {
"express": "3.x"
}
}
Once the package.json file is updated you’ll need to run the npm installation.
npm install
The second method is useful if you’ve already got a package.json file. You can use a lesser known option on npm install to automatically update your package.json – the save option.
npm install express --save
The project directory will now have a node_modules folder and inside it will be an express folder. Your application is now setup to start building.
First Application
To get rolling let’s build a very simple application to get familiar with the syntax of Express. This means creating a main file, in this case app.js.
The start of the file needs to include the express module using a require statement. Once included you can invoke it as a function which will return an Express server instance. This application instance will allow you to configure and add routes.
var express = require('express');
var app = express();
The next step is to add a route. This is a url that can be retrieved in the application. You build a route by calling app.METHOD where METHOD is an acceptable HTTP method like “get”. The route is passed the url that will be accessed, such as ‘/’ or the site root. The second parameter to a route is a callback to call when the url is retrieved.
The route callback takes in a req (request) and res (response) which are modified versions of the objects passed to the core request event. Express adds functionality to both objects but for this exercise we’ll concentrate on the response object.
With the response object the following code will do two things. It will set the content type header (Content-Type) using the res.type function. A text response will be sent back using res.send which will automatically set the content length header (Content-Length).
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.type('text/plain');
res.send('i am a beautiful butterfly');
});
The final thing we need to do in this simple example is have the app listen for incoming requests. This is done using the aptly named listen function. This function will take any valid parameters that you can pass in to the regular http server. In order to make it easy to change the port and support deploying to platforms likeModulus the port will be set to process.env.PORT or 4730 (a random port I chose). The process.env.PORT means if the PORT environment variable is passed in it will use it. This wraps up the basic app.
first.js
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.type('text/plain'); // set content-type
res.send('i am a beautiful butterfly'); // send text response
});
app.listen(process.env.PORT || 4730);
You can test this by running the file using:
node app.js
Then you may go to http://localhost:4730 in your browser and if all went well you’ll see ‘i am a beautiful butterfly’.
Basic REST API
Now that we have a very basic express application we can dive into a more complex application. If you need more information on what a RESTful API is check out theWikipedia article.
REST APIs are made up of four method types, GET, PUT, POST, and DELETE and with Express we can easily do them all. For the rest of this article we’re going to build a simple API that allows you to get and save quotes.
To get started we’ll start with a basic Express application that just has an array of quotes. Each quote is an object with the author and text.
quote.js
var express = require('express');
var app = express();
var quotes = [
{ author : 'Audrey Hepburn', text : "Nothing is impossible, the word itself says 'I'm possible'!"},
{ author : 'Walt Disney', text : "You may not realize it when it happens, but a kick in the teeth may be the best thing in the world for you"},
{ author : 'Unknown', text : "Even the greatest was once a beginner. Don't be afraid to take that first step."},
{ author : 'Neale Donald Walsch', text : "You are afraid to die, and you're afraid to live. What a way to exist."}
];
app.listen(process.env.PORT || 3412);
Now you’ll notice that this doesn’t really do anything. So let’s add a route to return all of the quotes in our array. Now, this is going to be really easy. We’re going to take advantage of a helper function on the response object, to send a json object.
app.get('/', function(req, res) {
res.json(quotes);
});
Let’s add the ability to retrieve a random quote. This, again, shouldn’t be hard addition. We’ll add a new route ‘/quote/random’; then we’ll calculate a random index, grab the quote, and return it.
app.get('/quote/random', function(req, res) {
var id = Math.floor(Math.random() * quotes.length);
var q = quotes[id];
res.json(q);
});
The next thing we’ll add in there is the ability to grab a single quote. The way you do this is by adding a “:param” to the route, so the route will look like “/quote/:id” and the id will be available using req.params.
app.get('/quote/:id', function(req, res) {
if(quotes.length <= req.params.id || req.params.id < 0) {
res.statusCode = 404;
return res.send('Error 404: No quote found');
}
var q = quotes[req.params.id];
res.json(q);
});
In the above the code you can see that we first check to make sure that the id requested is in the range of quotes we have. If no then we return a 404 error, meaning that the quote wasn’t found. In theory we’d probably return a nice error object in this case. If the request is good then we return the result found based on the id.
One item to note is that since we have “/quote/random” and “/quote/:id” we have to put the random route first. Why you ask? Well, this is because routes are checked in order and if it was the other way around “random” would be treated like an id.
So, I’m guessing you’ll want to be able to dynamically add quotes to the array. This will be done using a POST method to the API, this is done using app.post. The POST should have a JSON object for the new quote.
In order to get the body from a POST in express we have to add a piece of middleware to our application. This is done using bodyParser middleware. Body parser will pretty much do what it sounds like – parse the body of the request and then it sets the body property on the request object.
app.use(express.bodyParser());
The above should be added to the top of the application before we add any routes.
app.post('/quote', function(req, res) {
if(!req.body.hasOwnProperty('author') ||
!req.body.hasOwnProperty('text')) {
res.statusCode = 400;
return res.send('Error 400: Post syntax incorrect.');
}
var newQuote = {
author : req.body.author,
text : req.body.text
};
quotes.push(newQuote);
res.json(true);
});
At the beginning of our route function we check to make sure the body has both the “author” and “text” properties. If they don’t exist then we return an error. If the request is fine then we add it to our quotes and push back a true response.
The last thing thing we’ll add is the ability to delete a response. This will be achieved using the DELETE method.
app.delete('/quote/:id', function(req, res) {
if(quotes.length <= req.params.id) {
res.statusCode = 404;
return res.send('Error 404: No quote found');
}
quotes.splice(req.params.id, 1);
res.json(true);
});
The above function starts by checking the length of our quotes to make sure we don’t try to delete something that isn’t there. If no error we splice the array to remove the quote and return true to the client.
That pretty much covers the basics. Now, this is only a drop in the bucket of what Express has and can do. The entire project and source code for this is available on GitHub. Feel free to leave any questions below.
View more at: http://yoursmart.mobi
Post a Comment