Featured image of post How to Create a REST API with Node.js and Express in Under 15 Minutes

How to Create a REST API with Node.js and Express in Under 15 Minutes

A quick guide to building a functional REST API using Node.js and Express.js, perfect for beginners.

How to Create a REST API with Node.js and Express in Under 15 Minutes

This tutorial demonstrates how to quickly build a basic REST API using Node.js and Express.js. We’ll focus on the core concepts, making it easily digestible for beginners. While a fully-fledged API would require more robust error handling and security measures, this example provides a solid foundation.

Prerequisites:

Step 1: Project Setup

  1. Create a new directory for your project: mkdir my-rest-api
  2. Navigate into the directory: cd my-rest-api
  3. Initialize a Node.js project: npm init -y
  4. Install Express.js: npm install express

Step 2: Creating the API (app.js)

Create a file named app.js and paste the following code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
const express = require('express');
const app = express();
const port = 3000;

app.get('/api/users', (req, res) => {
  const users = [
    { id: 1, name: 'John Doe' },
    { id: 2, name: 'Jane Smith' },
  ];
  res.json(users);
});

app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

Explanation:

  • require('express'): Imports the Express.js library.
  • app.get('/api/users', ...): Defines a GET route for /api/users. This route will return a JSON array of users. req represents the request object, and res represents the response object.
  • res.json(users): Sends the users array as a JSON response.
  • app.listen(port, ...): Starts the server on port 3000.

Step 3: Run the API

Execute the following command in your terminal: node app.js

Step 4: Testing the API

Use a tool like Postman (https://www.postman.com/) or curl to test your API. Make a GET request to http://localhost:3000/api/users. You should receive a JSON response containing the user data.

Extending the API (Adding POST functionality):

Let’s add a POST route to create a new user. Modify your app.js file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const express = require('express');
const app = express();
const port = 3000;
app.use(express.json()); //This line is crucial for handling JSON in POST requests

let users = [
    { id: 1, name: 'John Doe' },
    { id: 2, name: 'Jane Smith' },
];

app.get('/api/users', (req, res) => {
  res.json(users);
});

app.post('/api/users', (req, res) => {
  const newUser = req.body;
  newUser.id = users.length + 1;
  users.push(newUser);
  res.status(201).json(newUser);
});

app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

Now you can send a POST request to http://localhost:3000/api/users with a JSON payload (e.g., {"name": "New User"}) to add a new user. The response will be the newly created user object. Remember that app.use(express.json()) is essential for parsing JSON from POST requests.

This expanded example provides a more complete foundation for building more complex REST APIs with Node.js and Express.js. Remember to adapt and expand upon this base to fit your specific needs and always prioritize security best practices in a production environment.