0
0
NodejsHow-ToBeginner · 4 min read

How to Create CRUD API in Node.js: Simple Guide

To create a CRUD API in Node.js, use the Express framework to define routes for Create, Read, Update, and Delete operations. Each route handles HTTP methods like POST, GET, PUT, and DELETE to manage data, often stored in memory or a database.
📐

Syntax

In Node.js, a CRUD API typically uses Express routes to handle HTTP methods:

  • POST for creating data
  • GET for reading data
  • PUT for updating data
  • DELETE for deleting data

Each route has a path and a callback function that processes the request and sends a response.

javascript
const express = require('express');
const app = express();
app.use(express.json());

// Create
app.post('/items', (req, res) => {
  // code to add item
});

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

// Update
app.put('/items/:id', (req, res) => {
  // code to update item by id
});

// Delete
app.delete('/items/:id', (req, res) => {
  // code to delete item by id
});

app.listen(3000, () => console.log('Server running on port 3000'));
💻

Example

This example shows a simple CRUD API managing a list of items stored in memory. It demonstrates how to add, view, update, and delete items using Express routes.

javascript
const express = require('express');
const app = express();
app.use(express.json());

let items = [];
let idCounter = 1;

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

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

// Update item by id
app.put('/items/:id', (req, res) => {
  const id = parseInt(req.params.id);
  const item = items.find(i => i.id === id);
  if (!item) return res.status(404).json({ error: 'Item not found' });
  item.name = req.body.name || item.name;
  res.json(item);
});

// Delete item by id
app.delete('/items/:id', (req, res) => {
  const id = parseInt(req.params.id);
  const index = items.findIndex(i => i.id === id);
  if (index === -1) return res.status(404).json({ error: 'Item not found' });
  items.splice(index, 1);
  res.status(204).send();
});

app.listen(3000, () => console.log('CRUD API running on http://localhost:3000'));
Output
CRUD API running on http://localhost:3000
⚠️

Common Pitfalls

Common mistakes when creating a CRUD API in Node.js include:

  • Not parsing JSON body with express.json(), causing req.body to be undefined.
  • Forgetting to handle errors like missing items on update or delete.
  • Using global variables for data storage in production instead of a database.
  • Not sending proper HTTP status codes (e.g., 201 for creation, 404 for not found).
javascript
/* Wrong: Missing JSON parser middleware */
app.post('/items', (req, res) => {
  // req.body will be undefined
  const item = { name: req.body.name };
  res.json(item);
});

/* Right: Use express.json() middleware */
const express = require('express');
const app = express();
app.use(express.json());
app.post('/items', (req, res) => {
  const item = { name: req.body.name };
  res.json(item);
});
📊

Quick Reference

Remember these key points when building a CRUD API in Node.js:

  • Use express.json() to parse JSON request bodies.
  • Define routes for each CRUD operation with correct HTTP methods.
  • Use unique IDs to identify resources.
  • Send appropriate HTTP status codes for success and errors.
  • For real apps, connect to a database instead of using in-memory arrays.

Key Takeaways

Use Express routes with POST, GET, PUT, DELETE to build CRUD APIs in Node.js.
Always parse JSON request bodies with express.json() middleware.
Handle errors and send proper HTTP status codes for better API behavior.
Store data in a database for production instead of in-memory variables.
Test each route to ensure it correctly creates, reads, updates, and deletes data.