APIs: How to Create APIs using Node.js and Express.js

APIs: How to Create APIs using Node.js and Express.js

Table of contents

No heading

No headings in the article.

APIs (Application Programming Interfaces) are an essential part of modern web development. They allow different software applications to communicate with each other, and share data and functionality. Here is an example of how to create APIs using Node.js and Express.js:

First, install the required packages by running the following command in the terminal:

npm install express body-parser cors

Then create a new file called server.js and add the following code:

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();

// middleware
app.use(cors());
app.use(bodyParser.json());

// route
app.get('/api/hello', (req, res) => {
  res.send('Hello World!');
});

app.post('/api/add', (req, res) => {
  const { num1, num2 } = req.body;
  const result = num1 + num2;
  res.json({ result });
});

// start server
const port = 3000;
app.listen(port, () => {
  console.log(`Server started on port ${port}`);
});

In this example, we use the express package to create an instance of the application. We also use the body-parser package to parse incoming request bodies and the cors package to enable cross-origin resource sharing.

We then define a GET route at /api/hello that simply returns a Hello World! message. We also define a POST route at /api/add takes two numbers as input, adds them together, and returns the result as a JSON object.

To start the server, we listen on port 3000 and log a message to the console.

To test the APIs, you can use a tool like Postman or curl. For example, to test the POST route, you can send a request with a JSON payload like this:

{
  "num1": 5,
  "num2": 10
}

The expected response should be:

{
  "result": 15
}

This is a simple example, but you can use the same techniques to create more complex APIs with more routes and functionality.