Can you explain the main principles of building RESTful services?
sobes.tech AI
Answer from AI
Principles of building RESTful services:
-
Resource-oriented: all objects and data are represented as resources with unique URIs (e.g.,
/users/123). -
Use of standard HTTP methods:
GET— retrieve a resourcePOST— create a resourcePUT— update a resourceDELETE— delete a resource
-
HTTP status codes: the service should return correct response codes (e.g., 200 OK, 201 Created, 404 Not Found, 400 Bad Request).
-
Statelessness: each client request must contain all necessary information for processing; the server does not store state between requests.
-
Use of data formats: usually JSON or XML for data transfer.
-
Hypermedia (HATEOAS): responses may contain links to related resources for navigation.
Example of a simple RESTful route in Node.js using Express:
const express = require('express');
const app = express();
app.use(express.json());
// Get user by ID
app.get('/users/:id', (req, res) => {
const userId = req.params.id;
// logic to get user
res.json({ id: userId, name: 'Ivan' });
});
// Create a new user
app.post('/users', (req, res) => {
const newUser = req.body;
// logic to create
res.status(201).json(newUser);
});
app.listen(3000);
This approach provides a standardized and convenient interface for interacting with the service.