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
- A server with a
/tasksroute that returns JSON - A 404 answer for unknown routes
- A client that calls the server and prints the answers
Steps
- Read the server: it checks
req.url. - Read
get: it wraps http.get in a promise. - Press Run to see both answers.
- 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
- Add a
/tasks/1route. - Accept new tasks with a POST request.
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();
});