codegurukool.com · Free coding tutorials & online compiler

Home › Node.js Tutorial › Live project: Mini task API

Live project: Mini task API

Build a small JSON API with the http module.

Use the http module, routes, JSON and promises to build and call an API.

What you will build

Steps

  1. Read the server: it checks req.url.
  2. Read get: it wraps http.get in a promise.
  3. Press Run to see both answers.
  4. Add a new task to the array.

Run it

Press Run to see the project work. Then change the data in the editor and run it again.

Challenge

Example code

const http = require("http");
const tasks = [
  { id: 1, title: "Learn Node.js", done: true },
  { id: 2, title: "Build an API", done: false }
];

const server = http.createServer(function (req, res) {
  if (req.url === "/tasks") {
    res.setHeader("Content-Type", "application/json");
    res.end(JSON.stringify(tasks));
  } else {
    res.statusCode = 404;
    res.end("Not found");
  }
});

function get(port, path) {
  return new Promise(function (resolve) {
    http.get({ port: port, path: path }, function (r) {
      let d = "";
      r.on("data", function (c) { d += c; });
      r.on("end", function () { resolve(r.statusCode + " " + d); });
    });
  });
}

server.listen(0, async function () {
  const port = server.address().port;
  console.log(await get(port, "/tasks"));
  console.log(await get(port, "/missing"));
  server.close();
});

Run this code in the online editor

← Node.js streams