Back
Close

ExpressJS and APIs

VonRickroll
1,515 views

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
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
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Feeling lazy? How about you...

Check out the solution
Press "run my code" to see solution
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants