Serving APIs with Express

As for all Node modules, to use Express you have to install it with npm. The example project we’re working from already specifies a dependency on Express, so all we have to do is run npm install. If you were making your own project, you’d want to run npm install --save express to pull down the latest Express available and record the dependency in your package.json file.

Let’s take a look at a Hello World Express app to get a feel for how it works. Then we’ll expand on this skeleton to make our own RESTful APIs. In the terminal, navigate to the hello subdirectory of the example project. Here is the content of the server.js file you’ll find there:

web-services/hello/server.js
 
#!/usr/bin/env node --harmony
 
'use strict'​;
 
const
 
express = require(​'express'​),
 
app = express();
 
app.use(express.logger(​'dev'​));
 
app.get(​'/api/:name'​, ​function​(req, res) {
 
res.json(200, { "hello": req.params.name });
 
});
 
app.listen(3000, ​function​(){
 
console.log(​"ready captain."​);
 
});

First, this program brings in the express module and creates an app. Like the request module we worked with in the last chapter, the express module is itself a function. When you call this function, Express creates an application context for you. By convention, we name this variable app.

Express functionality is provided through something called middleware, which are asynchronous functions that manipulate the request and response objects. To specify middleware for your app, you call app.use(), passing in the middleware you want. In our case, we’re using the logger middleware set to dev mode, which will log to the console all requests coming in.

Next we use app.get() to tell Express how we want to handle HTTP GET requests to the /api/:name path. The :name chunk in the path is called a named route parameter. When the API is hit, Express will grab that part of the URL and make it available in req.params.

In addition to get(), Express has put(), post(), and del() to register handlers for PUT, POST, and DELETE requests, respectively. In our case, we tell the response object, res, to send back as JSON an object whose hello key is set to the name parameter.

Finally, this program listens on TCP port 3000 for incoming HTTP requests, and logs a message to the console when it’s ready to receive connections. Let’s run the app to see what it does.

Running a Server with npm

Instead of starting the server with node directly, this time we’ll use npm. Open a terminal to the hello directory and run npm start:

 
$ ​npm start
 
 
> [email protected] start ./hello
 
> node --harmony server.js
 
 
ready captain.

npm knows how to run this server because of the scripts hash in the package.json file. If you open the package.json, you’ll find a section that looks like this:

 
"scripts"​: {
 
"start": ​"node --harmony ./server.js"
 
},

You can add more scripts to the scripts hash—for example, it’s common to add a test item so that you can run npm test to execute your project’s unit tests.

Testing REST Endpoints with curl

With the Hello server running, let’s try it out. In a separate console, request the /api/* path with curl:

 
$ ​curl -i http://localhost:3000/api/jimbo
 
HTTP/1.1 200 OK
 
X-Powered-By: Express
 
Content-Type: application/json
 
Content-Length: 22
 
Date: Tue, 10 Sep 2013 14:41:22 GMT
 
Connection: keep-alive
 
 
{
 
"hello": "jimbo"
 
}

curl is a useful command-line tool for issuing HTTP requests to a given server. Adding the -i flag tells curl that it should output the HTTP headers in addition to the JSON body. Back in the server terminal, you should see this (thanks to the logger middleware):

 
GET /api/ 200 7ms - 22b

OK, now that we’ve got the basic outline of an Express REST service under control, let’s build something with a bit more bite to it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.5.86