HTTP (HyperText Transfer Protocol) methods, also known as HTTP verbs, define the action to be performed on a given resource on the server. When a client (such as a web browser) sends a request to the server, it uses one of these HTTP methods to indicate the desired operation. HTTP methods are fundamental to web development, as they dictate how data is requested or manipulated on the server.
In this chapter, we will explore all HTTP methods from basic to advanced, providing clear examples and explanations to fully understand each method.
There are several HTTP methods that are widely used in web applications, each designed for a specific type of operation. The most commonly used methods are:
GET
POST
PUT
DELETE
PATCH
OPTIONS
HEAD
Other methods, such as TRACE
and CONNECT
, exist but are used less frequently.
The GET
method is used to retrieve data from a server. It is a safe and idempotent method, meaning that multiple identical GET
requests will have no side effects and will produce the same result.
GET
request is made to the /search
endpoint, and the query parameter is appended to the URL as a query string.query
parameter.When you enter a search term and submit the form, the browser navigates to a URL like:
/search?query=term
The POST
method is used to send data to the server, typically to create a new resource. Unlike GET
, the POST
method does not append data to the URL; instead, the data is sent in the body of the request.
POST
request is made to the /submit
endpoint, and the username
and password
fields are sent in the body of the request.Submitting this form sends the data securely to the server without including it in the URL.
The PUT
method is used to update an existing resource on the server. It can also be used to create a resource if it doesn’t already exist. Like POST
, the PUT
method sends data in the body of the request.
fetch('/user/123', {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: 'newUsername',
email: 'newEmail@example.com'
})
});
PUT
request is sent to the /user/123
endpoint to update the user with ID 123
with new username and email data.PUT
requests with the same data will produce the same result.The DELETE
method is used to remove a resource from the server. Like PUT
, it is idempotent—repeated DELETE
requests for the same resource will have the same effect.
fetch('/user/123', {
method: 'DELETE'
});
DELETE
request to remove the user with ID 123
.The PATCH
method is used to partially update a resource. Unlike PUT
, which replaces the entire resource, PATCH
only updates the specified fields.
fetch('/user/123', {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: 'newEmail@example.com'
})
});
PATCH
request is made to update only the email
field of the user with ID 123
.The OPTIONS
method is used to describe the communication options for a given resource. It is commonly used in CORS (Cross-Origin Resource Sharing) to check which HTTP methods and headers are supported by the server for a specific resource.
fetch('/resource', {
method: 'OPTIONS'
});
/resource
endpoint.The HEAD
method is similar to GET
, but it only requests the headers and not the body of the resource. It is useful for checking meta-information, such as the size or content type of a resource, without downloading the actual content.
fetch('/resource', {
method: 'HEAD'
});
/resource
endpoint without fetching the body.GET
.GET
, PUT
, DELETE
, and HEAD
are all idempotent methods, while POST
and PATCH
are not.example.com
cannot make requests to another-site.com
unless permitted by CORS.OPTIONS
method to check whether the cross-origin request is allowed.GET
: Read dataPOST
: Create dataPUT
: Update or replace dataDELETE
: Delete dataPATCH
: Partially update dataHere’s an example of how different HTTP methods are used in a simple REST API for managing users.
// Express.js REST API example
const express = require('express');
const app = express();
app.use(express.json());
// Data
let users = [];
// GET method to retrieve users
app.get('/users', (req, res) => {
res.json(users);
});
// POST method to create a new user
app.post('/users', (req, res) => {
const newUser = req.body;
users.push(newUser);
res.status(201).json(newUser);
});
// PUT method to update a user by ID
app.put('/users/:id', (req, res) => {
const id = req.params.id;
const updatedUser = req.body;
users = users.map(user => (user.id === id ? updatedUser : user));
res.json(updatedUser);
});
// DELETE method to delete a user by ID
app.delete('/users/:id', (req, res) => {
const id = req.params.id;
users = users.filter(user => user.id !== id);
res.status(204).send();
});
// PATCH method to partially update a user by ID
app.patch('/users/:id', (req, res) => {
const id = req.params.id;
const updatedFields = req.body;
users = users.map(user =>
user.id === id ? { ...user, ...updatedFields } : user
);
res.json(users.find(user => user.id === id));
});
// Start the server
app.listen(3000, () => {
console.log('Server running on port 3000');
});
In this example:
GET /users
retrieves the list of users.POST /users
creates a new user.PUT /users/:id
updates an existing user.DELETE /users/:id
deletes a user.PATCH /users/:id
partially updates a user.HTTP methods form the backbone of communication between clients and servers. Each method has a specific role, whether it's retrieving data, creating resources, updating resources, or deleting resources. Understanding these methods is crucial for web development, REST API design, and efficient client-server communication. Happy coding !❤️