Building a REST API with Node.js and Express

ZuZulfikar Achyar
June 22, 2024
Building a REST API with Node.js and Express

Node.js and Express are a classic combination for building fast and scalable REST APIs.

Setup

First, initialize a Node.js project and install Express:

npm init -y
npm install express

Create the Server

Create a file named index.js:

const express = require('express');
const app = express();
const port = 3000;

// Middleware to parse JSON
app.use(express.json());

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

// A simple POST route
app.post('/echo', (req, res) => {
  res.json(req.body);
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});

Run the server with node index.js and you'll have a working API.

Let's build something together.

I'm currently available for freelance work and open to discussing new projects.

Contact Details

zulfikarachyar@gmail.com