RESTful API
RESTful API (Representational State Transfer API) is an application programming interface design approach 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 2000 doctoral dissertation and emphasizes statelessness, client-server separation, a uniform interface, and cacheability. At its core, a RESTful API performs create, read, update, and delete (CRUD) operations on resources over the HTTP protocol.
Characteristics of RESTful APIs
- Statelessness: Every request carries all the information it needs (such as authentication credentials), and the server does not retain client state between requests.
- Client-server architecture: The client handles the user interface and user experience, while the server handles data storage and business logic; the two are independent of each other.
- Uniform interface: A RESTful API operates through standard HTTP verbs (GET, POST, PUT, DELETE, and so on), with a consistent interface design that is easy to understand and use.
- Cacheability: Responses can be marked as cacheable to improve performance and reduce server load.
- Layered system: Intermediate layers (such as load balancers and proxy servers) improve the scalability and security of the system.
- Code on demand: The server can send code or scripts to the client for execution to extend client functionality.
HTTP verbs
- GET: Used to read a resource and has no effect on resources on the server.
- POST: Used to create a new resource or submit data; the server creates a new resource after processing the request.
- PUT: Used to update an existing resource by overwriting the resource on the server with the data supplied by the client.
- DELETE: Used to delete a resource on the server.
- PATCH: Used to partially update a resource, changing only part of its content.
URL design
A RESTful API uses uniform resource identifiers (URIs) to represent resources, and each resource has a unique URL. Relationships between resources are expressed through URL hierarchy.
Example URL design:
GET /books: Retrieve the list of all books.GET /books/{id}: Retrieve the book with a specific ID.POST /books: Create a new book.PUT /books/{id}: Update the book with a specific ID.DELETE /books/{id}: Delete the book with a specific ID.
Response status codes
A RESTful API uses HTTP status codes to indicate the outcome of a request:
- 200 OK: The request succeeded and data is returned.
- 201 Created: The resource was created successfully.
- 204 No Content: The request succeeded with no content returned.
- 400 Bad Request: The request is invalid or malformed.
- 401 Unauthorized: The request is not authorized.
- 404 Not Found: The requested resource does not exist.
- 500 Internal Server Error: An internal server error occurred.
Example
The following is a simple RESTful API example that uses Node.js and the Express framework to build 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 a book
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
A RESTful API is a simple, flexible, and easily extensible approach to designing web services. By operating through the standard HTTP protocol and verbs, it makes communication between client and server more intuitive and efficient. It suits web applications of every scale, from small projects to large distributed systems.
