RESTful API
RESTful API (Representational State Transfer API) is an application interface design method based on the REST architectural style, widely used for data exchange between Web services and systems. REST was first proposed by Roy Fielding in his doctoral dissertation in 2000, emphasizing principles such as statelessness, client-server separation, unified interface, and cacheability. The core of RESTful API is to create, read, update, and delete resources (CRUD) through the HTTP protocol.
Features of RESTful API
Stateless: Each request contains all necessary information (such as authentication information), and the server does not retain the client's state between requests.
Client-Server Architecture: The client is responsible for the user interface and user experience, and the server is responsible for data storage and business logic, which are independent of each other.
Uniform Interface: RESTful API uses standard HTTP verbs (GET, POST, PUT, DELETE, etc.) for operation, and the interface design specifications are consistent, easy to understand and use.
Cacheability: Response data can be marked as cacheable to improve performance and reduce server load.
Layered System: Improve the scalability and security of the system through the middle layer (such as load balancer, proxy server).
Encoding on Demand: The server can send code or scripts to the client for execution to enhance client functionality.
HTTP Verbs
GET: Used to read resources without any impact on resources on the server.
POST: Used to create new resources or submit data. The server creates new resources after processing the request.
PUT: used to update existing resources, overwriting the resources on the server with the data provided by the client.
DELETE: used to delete resources on the server.
PATCH: used to partially update resources and change part of the content of resources.
URL design
RESTful API uses Uniform Resource Identifiers (URIs) to represent resources, and each resource has a unique URL. The relationship between resources is represented by the URL hierarchy.
Example URL design:
GET /books
: Get a list of all books.GET /books/{id}
: Get a book with a specific ID.POST /books
: Create a new book.PUT /books/{id}
: Update a book with a specific ID.DELETE /books/{id}
: Delete a book with a specific ID.
Response status code
RESTful API uses HTTP status codes to indicate the processing results of the request:
- 200 OK: The request is successful and data is returned.
- 201 Created: The resource is created successfully.
- 204 No Content: Request successful, no content returned.
- 400 Bad Request: Request invalid or malformed.
- 401 Unauthorized: Request unauthorized.
- 404 Not Found: Requested resource does not exist.
- 500 Internal Server Error: Server internal error.
Example
The following is a simple RESTful API example that uses Node.js and Express framework to create a book management system.
Server code (Node.js + Express)
const express = require('express');
const app = express();
app.use(express.json());
let books = [
{ id: 1, title: '1984', author: 'George Orwell' },
{ id: 2, title: 'To Kill a Mockingbird', author: 'Harper Lee' }
];
// Get all books
app.get('/books', (req, res) => {
res.json(books);
});
// Get a specific book
app.get('/books/:id', (req, res) => {
const book = books.find(b => b.id === parseInt(req.params.id));
if (!book) return res.status(404).send('Book not found');
res.json(book); }); // Create a new book app.post('/books', (req, res) => { const book = { id: books.length + 1, title: req.body.title, author: req.body.author }; books.push(book); res.status(201).json(book); }); // Update a book app.put('/books/:id', (req, res ) => { const book = books.find(b => b.id === parseInt(req.params.id)); if (!book) return res.status(404).send('Book not found'); book.title = req.body.title; book.author = req.body.author; res.json(book); }); // Delete books app.delete('/books/:id', (req, res) => {
const book = books.find(b => b.id === parseInt(req.params.id));
if (!book) return res.status(404).send('Book not found');
const index = books.indexOf(book);
books.splice(index, 1);
res.status(204).send();
});
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
Summary
RESTful API is a simple, flexible, and easy-to-extend Web service design approach that operates through standard HTTP protocols and verbs, making communication between clients and servers more intuitive and efficient. It is suitable for Web applications of all sizes, from small projects to large distributed systems.