一起学习网 一起学习网


Build RESTful API with Node.js

开发 Node.js, Express, RESTful API, CRUD operations, tutorial 04-17

Creating a Simple RESTful API with Node.js and Express

In this tutorial, we will build a simple RESTful API using Node.js and the Express framework. This API will allow users to perform basic CRUD (Create, Read, Update, Delete) operations on a list of items. We'll go through the process step-by-step, providing code and explanations along the way.

Prerequisites

Before we start, make sure you have the following installed:

  • Node.js
  • npm (Node Package Manager)

Step 1: Setting Up the Project

Create a new directory for your project and navigate into it using the terminal:

mkdir simple-api
cd simple-api

Initialize a new Node.js project. This will create a package.json file:

npm init -y

Install Express as a dependency:

npm install express

Step 2: Create the Server

Create a file named server.js. This is where we'll set up a basic Express server:

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

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

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

Step 3: Define the Data Structure

For simplicity, we'll use an array to store our items. In a real-world scenario, you would typically use a database.

In server.js, define an array to hold the data:

let items = [
  { id: 1, name: 'Item One' },
  { id: 2, name: 'Item Two' },
];

Step 4: Create the Routes

We'll create the necessary endpoints for CRUD operations: GET, POST, PUT, and DELETE.

4.1 GET All Items

Add the following code to retrieve all items:

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

4.2 GET a Single Item

Add a route to get a specific item by ID:

app.get('/items/:id', (req, res) => {
  const itemId = parseInt(req.params.id, 10);
  const item = items.find(i => i.id === itemId);
  if (item) {
    res.json(item);
  } else {
    res.status(404).json({ message: 'Item not found' });
  }
});

4.3 POST a New Item

Add a route to create a new item:

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

4.4 PUT to Update an Item

Add a route to update an existing item:

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

4.5 DELETE an Item

Add a route to delete an item:

app.delete('/items/:id', (req, res) => {
  const itemId = parseInt(req.params.id, 10);
  const itemIndex = items.findIndex(i => i.id === itemId);

  if (itemIndex !== -1) {
    items.splice(itemIndex, 1);
    res.status(204).end();
  } else {
    res.status(404).json({ message: 'Item not found' });
  }
});

Step 5: Test the API

Start the server using the following command:

node server.js

Use an API testing tool like Postman or Insomnia to test the routes by sending HTTP requests to http://localhost:3000/items.

Conclusion

Congratulations! You have successfully created a simple RESTful API using Node.js and Express. This basic setup can be expanded and customized for more complex applications, such as integrating a database for persistent storage.


编辑:一起学习网