Building a News API with Node.js

JavaScriptJavaScriptBeginner
Practice Now

Introduction

In this project, you will learn how to create a simple news API using Node.js. You will learn how to create a server, handle different routes, and return news data in a specific format.

👀 Preview

curl http://localhost:8080/news
## Output:
## [{"channelId":"5572a108b3cdc86cf39001cd","name":"National Focus"},{"channelId":"5572a108b3cdc86cf39001ce","name":"International Focus"}]

curl http://localhost:8080
## Output:
## 404

🎯 Tasks

In this project, you will learn:

  • How to create a server using Node.js
  • How to handle the /news route and return news data
  • How to handle other routes and return a 404 response

🏆 Achievements

After completing this project, you will be able to:

  • Understand the basics of creating a server using Node.js
  • Implement a simple API to return news data
  • Handle different routes and provide appropriate responses

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/NetworkingGroup(["`Networking`"]) javascript/AdvancedConceptsGroup -.-> javascript/es6("`ES6 Features`") javascript/NetworkingGroup -.-> javascript/http_req("`HTTP Requests`") subgraph Lab Skills javascript/es6 -.-> lab-301448{{"`Building a News API with Node.js`"}} javascript/http_req -.-> lab-301448{{"`Building a News API with Node.js`"}} end

Create a Server

To get started, open the editor. You should see a file from the editor - "app.js".

In this step, you will learn how to create a server using Node.js. Follow the steps below to complete this step:

  1. Open the app.js file in your coding environment.

  2. Import the http module, which provides the functionality to create a server:

    const http = require("http");
  3. Create a new server using the createServer() method:

    const serve = http.createServer();
  4. Add an event listener to the server to handle incoming requests:

    serve.on("request", (req, res) => {
      // TODO: Add code to handle the request
    });
  5. Start the server and listen on port 8080:

    serve.listen(8080, () => {
      console.log("The service has been started!");
    });

Handle the /news Route

In this step, you will learn how to handle the /news route and return news data. Follow the steps below to complete this step:

  1. Inside the request event listener, set the response header to use the utf8 format:

    res.setHeader("Content-type", "text/html;charset=utf8");
  2. Check the requested URL:

    if (req.url == "/news") {
      // Handle the /news route
    } else {
      // Handle other routes
    }
  3. Prepare the news data in the required format:

    const data = [
      {
        channelId: "5572a108b3cdc86cf39001cd",
        name: "National Focus"
      },
      {
        channelId: "5572a108b3cdc86cf39001ce",
        name: "International Focus"
      }
    ];
  4. Send the news data as the response:

    res.end(JSON.stringify(data));

Handle Other Routes

In this step, you will learn how to handle other routes that are not /news.

  1. Inside the request event listener, add an else block to handle other routes:

    if (req.url == "/news") {
      // Handle the /news route
      // ...
    } else {
      // Handle other routes
      res.end("404");
    }
  2. In the else block, send a 404 response to indicate that the requested route was not found.

Now, your app.js file should look like this:

const http = require("http");
const serve = http.createServer();

serve.on("request", (req, res) => {
  // TODO: Add code to handle the request
  res.setHeader("Content-type", "text/html;charset=utf8");
  console.log(req.url);
  if (req.url == "/news") {
    const data = [
      {
        channelId: "5572a108b3cdc86cf39001cd",
        name: "National Focus"
      },
      {
        channelId: "5572a108b3cdc86cf39001ce",
        name: "International Focus"
      }
    ];

    res.end(JSON.stringify(data));
  } else {
    res.end("404");
  }
});

serve.listen(8080, () => {
  console.log("The service has been started!");
});

Test the Server

  1. Run the server using the following command in the terminal:

    node app.js
  2. Open a new terminal again and verify that the terminal is correct with the following command:

curl http://localhost:8080/news
## Output:
## [{"channelId":"5572a108b3cdc86cf39001cd","name":"National Focus"},{"channelId":"5572a108b3cdc86cf39001ce","name":"International Focus"}]

curl http://localhost:8080
## Output:
## 404

Congratulations! You have successfully created a news API using Node.js.

Summary

Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like