ExpressJS and APIs

VonRickroll
124 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

EXPRESS

Express is a cool NodeJS framework to quickly bootstrap a web app or a web API. But how easy is it actually? Let's dive right in with some Express apis.

Get APIs

To make an API, you first need to require the Express router:

var express = require('express');
var router = express.Router();

Then, the router object allows you to declare apis with the standard HTTP verbs, get post put and delete. Here is a GET request

router.get('/path', function(req, res) {

});
  • The req object represents the request, and has a bunch of info on the users' request. Most importantly, you will want to take a look at req.body, but that's for an other lesson ;)
  • The res object is your response. If you want to return a JS object, in the case of an API, you will use the send method:
res.send({
  didItWork: 'yes'
});

About the path of the query, you can add parameters to make your API more dynamic, by adding a colon before the name of the variable you want

router.get('/path:myParameter', function(req, res) {
  ...
});

The variable will then be available under req.params.myParameter

Let's try it out!

Here's an API that I started out for you. It's supposed to return content of a user database (a simple static file). Being really lazy, I left out one of the APIs blank and you will have to fill it for me.

I plugged some automated testing to check that everything is in order but you can test your API yourself using the interface once you click "Run my Code".

Fill out the API
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var express = require('express');
var router = express.Router();
// Our database :
var userbase = require('./userbase');
router.get('/users', function(req, res) {
res.send(userbase);
});
router.get('/users/:index', function(req, res) {
var index = parseInt(req.params.index); // Don't forget to parse as a number :)
res.send(userbase[index]);
});
// TODO create an API with the form /users/:index/:amount returning `amount` users starting at index `index`
router.get('/users/:index/:amount', function(req, res) {
// TODO
});
//
module.exports = router;
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Feeling lazy? How about you...

Check out the solution
1
2
Press "run my code" to see solution
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content