Creating a CRUD API Using Express.js

Posted by

In this tutorial, we will learn how to create a CRUD (Create, Read, Update, Delete) API using Express.js. Express.js is a popular Node.js web application framework that provides a robust set of features for building web applications, including RESTful APIs.

To get started, you will need to have Node.js installed on your machine. If you don’t have it installed, you can download it from the official website: https://nodejs.org/

Once you have Node.js installed, you can create a new directory for your project and navigate to it using the terminal/command prompt. Next, you will need to initialize a new Node.js project by running the following command:

npm init -y

This will create a package.json file in your project directory, which will store information about your project and its dependencies.

Next, you will need to install Express.js as a dependency for your project. You can do this by running the following command:

npm install express

Now that you have Express.js installed, you can start building your CRUD API. Create a new JavaScript file (for example, app.js) in your project directory and require Express at the top of the file:

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

Next, you can define routes for handling the CRUD operations. Let’s start by defining a route for reading data from the API. In Express, you can define a route using the app.get() method. Here’s an example route that will return a list of items:

const items = [
  { id: 1, name: 'Item 1' },
  { id: 2, name: 'Item 2' },
  { id: 3, name: 'Item 3' }
];

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

In the example above, we defined a route for /items that will return the items array as JSON when a GET request is made to that route.

Next, let’s define routes for creating, updating, and deleting items. You can define these routes using the app.post(), app.put(), and app.delete() methods, respectively. Here are examples of these routes:

app.post('/items', (req, res) => {
  const newItem = { id: items.length + 1, name: req.body.name };
  items.push(newItem);
  res.status(201).json(newItem);
});

app.put('/items/:id', (req, res) => {
  const itemId = parseInt(req.params.id);
  const updatedItem = { id: itemId, name: req.body.name };
  const index = items.findIndex(item => item.id === itemId);
  if (index !== -1) {
    items[index] = updatedItem;
    res.json(updatedItem);
  } else {
    res.status(404).json({ message: 'Item not found' });
  }
});

app.delete('/items/:id', (req, res) => {
  const itemId = parseInt(req.params.id);
  const index = items.findIndex(item => item.id === itemId);
  if (index !== -1) {
    items.splice(index, 1);
    res.sendStatus(204);
  } else {
    res.status(404).json({ message: 'Item not found' });
  }
});

In the examples above, we defined routes for creating a new item (POST /items), updating an existing item (PUT /items/:id), and deleting an item (DELETE /items/:id). These routes use the req.body and req.params objects to access request body data and URL parameters, respectively.

Finally, you will need to start the Express server and listen on a port for incoming requests. You can do this by adding the following code at the end of your app.js file:

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Now, you can run your Express API by executing the following command in the terminal/command prompt:

node app.js

Your CRUD API should now be up and running, and you can start making requests to it using tools like Postman or cURL. Congratulations on building your first CRUD API with Express.js!