Sobes.tech
Junior — Middle

What are the main principles underlying RESTful API and how are they implemented?

sobes.tech AI

Answer from AI

RESTful API is based on several key principles:

  1. Client-server architecture — the client and server are separated, allowing independent development.
  2. Statelessness — each request from the client to the server must contain all the information needed; the server does not store state between requests.
  3. Caching — responses can be cached to improve performance.
  4. Uniform interface — uses a standard set of HTTP methods (GET, POST, PUT, DELETE, etc.) and clear resource identification via URLs.
  5. Layered system — architecture can have multiple layers (proxies, load balancers, etc.) that do not affect client-server interaction.
  6. Code on demand (optional) — the server can send executable code to the client.

Implementation in Node.js typically includes:

  • Defining resources via routes (e.g., /users, /products).
  • Using HTTP methods for CRUD operations:
    • GET — retrieve data
    • POST — create
    • PUT/PATCH — update
    • DELETE — delete
  • Sending responses with appropriate HTTP status codes (200, 201, 404, 500, etc.).

Example of a simple RESTful route in Express.js:

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

let users = [];

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

app.post('/users', (req, res) => {
  const user = req.body;
  users.push(user);
  res.status(201).json(user);
});

app.listen(3000);