Rest APIs CRUD

Rest APIs CRUD

CRUD (Create, Read, Update, Delete) operations are the foundation of most applications, enabling users to interact with data in meaningful ways. REST APIs, following the principles of Representational State Transfer, provide a standard approach to achieving CRUD functionality.

CRUD with REST: overview

Each CRUD operation aligns with specific HTTP methods:

  • Create: Use POST to add new resources.
  • Read: Use GET to retrieve existing resources.
  • Update: Use PUT or PATCH to modify resources.
  • Delete: Use DELETE to remove resources.

Building a REST API Using Node.js and Express

To create a REST API for the above CRUD operations, use Node.js with the Express framework.

Install dependencies:

bash

npm install express body-parser

Example code

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.json());

let customers = [];

// Create
app.post('/api/customers', (req, res) => {
  const customer = req.body;
  customers.push(customer);
  res.status(201).json(customer);
});

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

// Update
app.put('/api/customers/:id', (req, res) => {
  const id = parseInt(req.params.id);
  const updatedCustomer = req.body;
  customers[id] = updatedCustomer;
  res.json(updatedCustomer);
});

// Delete
app.delete('/api/customers/:id', (req, res) => {
  const id = parseInt(req.params.id);
  customers.splice(id, 1);
  res.status(204).send();
});

// Start Server
app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});

Consuming CRUD API

Below are examples for each operation using REST APIs with multiple technologies.

1. Create (POST)

The POST method is used to create a new resource on the server by sending data in the request body.

Endpoint

POST /api/customers

Example payload

{
  "name": "John Doe",
  "email": "john.doe@example.com",
  "active": true
}

Examples by technology:

JavaScript (Axios)

const axios = require('axios');
axios.post('https://example.com/api/customers', {
  name: 'John Doe',
  email: 'john.doe@example.com',
  active: true
})
  .then(response => console.log('Created:', response.data))
  .catch(error => console.error(error));

Python (Requests)

import requests

url = 'https://example.com/api/customers'
data = {
    'name': 'John Doe',
    'email': 'john.doe@example.com',
    'active': True
}

response = requests.post(url, json=data)
print('Created:', response.json())

2. Read (GET)

The GET method retrieves data from the server, typically fetching one or more resources.

Endpoint

GET /api/customers

Examples by technology:

JavaScript (Axios)

axios.get('https://example.com/api/customers')
  .then(response => console.log('Data:', response.data))
  .catch(error => console.error(error));

Python (Requests)

response = requests.get('https://example.com/api/customers')
print('Data:', response.json())

3. Update (PUT)

The PUT method updates an existing resource by sending the modified data in the request body. Use PATCH for partial updates.

Endpoint

PUT /api/customers/1

Example payload

{
  "name": "John Updated",
  "email": "john.updated@example.com",
  "active": false
}

Examples by technology:

JavaScript (Axios)

axios.put('https://example.com/api/customers/1', {
  name: 'John Updated',
  email: 'john.updated@example.com',
  active: false
})
  .then(response => console.log('Updated:', response.data))
  .catch(error => console.error(error));

Python (Requests)

response = requests.put(
    'https://example.com/api/customers/1',
    json={
        'name': 'John Updated',
        'email': 'john.updated@example.com',
        'active': False
    }
)
print('Updated:', response.json())

4. Delete (DELETE)

The DELETE method removes a resource from the server, typically identified by its unique ID.

Endpoint

DELETE /api/customers/1

Examples by technology:

JavaScript (Axios)

axios.delete('https://example.com/api/customers/1')
  .then(response => console.log('Deleted:', response.data))
  .catch(error => console.error(error));

Python (Requests)

response = requests.delete('https://example.com/api/customers/1')
print('Deleted:', response.status_code)

Notable libraries and example projects

  1. NestJSX CRUD - Framework on top of NestJS for building CRUD Apps
  2. Django Ninja CRUD - built-in CRUD for Django Ninja Projects
  3. PHP CRUD API - Single file CRUD API on top of SQL database