A REST API or Representational State Transfer API, is a set of rules that allows different applications to communicate with each other over the internet. It enables clients, such as web browsers or mobile apps, to send requests to a server and receive data or perform actions. REST APIs are widely used because they are simple, flexible, and work with standard HTTP methods.
- Uses endpoints (URLs) to identify specific resources.
- Relies on standard HTTP methods such as GET, POST, PUT, and DELETE.
- Commonly returns responses in JSON format.
- Supports scalable and platform-independent communication.
- Widely used in web services, mobile apps, and cloud applications.
Principles of REST API
REST APIs follow a set of architectural principles that make them scalable, simple, and widely usable across the web. Fundamental principles that define their architecture and functionality:
- Statelessness: Each request from a client to the server must contain all the necessary information, and the server does not store session-related data.
- Client-Server Architecture: The client and server are separate entities, that allow independent development and scalability.
- Uniform Interface: A consistent way of accessing resources, typically via standardized HTTP methods (GET, POST, PUT, PATCH, DELETE).
- Cacheability: Responses from the server should indicate whether they can be cached to improve performance.
- Layered System: The architecture should support multiple layers (such as load balancers, authentication servers, and data storage) without affecting the client-server interaction.
- Code on Demand : The server can send executable code to the client to enhance functionality, though this is rarely used.
HTTP Methods Used in API
In RESTful APIs, HTTP methods define the actions to be performed on resources. Each HTTP method corresponds to a specific operation in the CRUD (Create, Read, Update, Delete) cycle. Here’s an explanation of the commonly used HTTP methods:
1. GET
It is used to retrieve an existing resource from the server. The server responds with the resource's data, often in JSON or XML format. It is used to read the data.
GET http://example.com/api/users
GET http://example.com/api/users/123
2. POST
It is used to add new resource on the server. It sends data to the server as part of the request body, typically in JSON or XML format.
POST /api/users
{
"name": "John Doe",
"email": "geeks.doe@example.com"
}
3. PUT
It is used to update an existing resource by sending a complete representation of the resource to the server. The server replaces the current data with the new data provided in the request body.
PUT /users/1
{
"name": "John Doe",
"email": "john.doe@example.com"
}
4. PATCH
It is used to modify specific fields of an existing resource. Instead of sending the entire resource, the client sends only the data that needs to be changed, making updates more efficient when only a few attributes require modification.
PATCH /users/1
{
"email": "newemail@example.com"
}
5. DELETE
This method is used to delete a resource from the server. Once executed successfully, it usually returns a status code indicating the deletion has been completed, such as 200 OK or 204 No Content. It is used to delete the data.
DELETE http://example.com/api/users/123Common HTTP Status Codes in REST APIs
Following HTTP status codes indicate the result of the request:
- 200 OK: The request was successful, and the server returned the requested data.
- 201 Created: A new resource has been successfully created (usually returned for POST requests).
- 400 Bad Request: The request is malformed or missing required data.
- 401 Unauthorized: The request requires authentication, and the user is not authorized.
- 404 Not Found: The requested resource was not found.
- 500 Internal Server Error: The server encountered an unexpected condition.
Creating a REST API
You can create a simple REST API in using the built-in http module or Express.js framework, simplifying routing and middleware handling.
Step 1: Create and Configure the Project
Create a new Node.js project, initialize package.json, and install Express using the following commands:
mkdir node-app
cd node-app
Step 2: Install Express
npm init -y
npm install express
Step 3: Create the Server
Creating a REST API in NodeJS using Express
const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());
app.get('/users', (req, res) => {
res.json({ message: 'Returning list of users' });
});
app.post('/users', (req, res) => {
const newUser = req.body;
res.json({ message: 'User created', user: newUser });
});
app.put('/users/:id', (req, res) => {
const userId = req.params.id;
const updatedUser = req.body;
res.json({ message: `User with ID ${userId} updated`, updatedUser });
});
app.delete('/users/:id', (req, res) => {
const userId = req.params.id;
res.json({ message: `User with ID ${userId} deleted` });
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Run the server
node app.jsOutput
Open the http://localhost:3000 on the postman to check the API is working properly or not.
In this example
- GET /users: This route fetches the list of users (or mock data in this case).
- POST /users: This route accepts JSON data from the client to create a new user.
- PUT /users/:id: This route updates the information of a user based on the user ID provided in the URL.
- DELETE /users/:id: This route deletes a user with the specified ID.