HTTP Methods
RESTful APIs use standard HTTP methods (GET, POST, PUT, PATCH, DELETE) to perform actions on resources:
- GET: Retrieves a representation of a resource (e.g., get user information).
- POST: Creates a new resource (e.g., add a new product to a shopping cart).
- PUT: Updates an existing resource (e.g., modify user profile information).
- PATCH: Makes partial updates to a resource (e.g., change a user’s password).
- DELETE: Deletes a resource (e.g., remove an item from a list).
const express = require('express');
const app = express();
const port = 3000;
// Middleware to parse JSON bodies
app.use(express.json());
// GET: Retrieves a representation of a resource from the server
app.get('/resource', (req, res) => {
// Here you would retrieve and return the resource
res.send('GET request to /resource');
});
// POST: Sending resource to the server
app.post('/resource', (req, res) => {
// Here you would process the resource sent in the request body
console.log('Received resource:', req.body);
res.send('POST request to /resource');
});
// PUT: To replace or update an entire resource or replace it with a new representation
app.put('/resource/:id', (req, res) => {
// Here you would update the resource with the specified ID
console.log('Updated resource with ID', req.params.id);
res.send('PUT request to /resource/:id');
});
// PATCH: To make partial updates to a resource
app.patch('/resource/:id', (req, res) => {
// Here you would apply partial updates to the resource with the specified ID
console.log('Patched resource with ID', req.params.id);
res.send('PATCH request to /resource/:id');
});
// DELETE: Deletes a resource
app.delete('/resource/:id', (req, res) => {
// Here you would delete the resource with the specified ID
console.log('Deleted resource with ID', req.params.id);
res.send('DELETE request to /resource/:id');
});
// Start the server
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
Output:
GET /resource: Retrieves a representation of a resource.
POST /resource: Sends a resource to the server.
PUT /resource/:id: Replaces or updates an entire resource.
PATCH /resource/:id: Makes partial updates to a resource.
DELETE /resource/:id: Deletes a resource.
What makes an API RESTful?
An API (Application Programming Interface) acts as a messenger between different software applications. It defines a set of rules, protocols, and specifications for how applications request data, exchange information, and receive responses.
Table of Content
- Introduction to REST API
- HTTP Methods
- Representation
- Clinet-Server
- Stateless Communication
- Resource-Based
- Self-Descriptive Messages
- Hypermedia (HATEOAS – Hypermedia as the Engine of Application State)
- Best Practices for Designing Robust and User-Friendly RESTful APIs
Contact Us