HTTP Methods

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.

Overview of HTTP Methods

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.

GET Method

Basic Explanation

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.

Example

				
					<form action="/search" method="GET">
  <label for="query">Search:</label>
  <input type="text" id="query" name="query">
  <input type="submit" value="Search">
</form>

				
			

Explanation

  • In this example, when the form is submitted, a GET request is made to the /search endpoint, and the query parameter is appended to the URL as a query string.
  • The server receives this request and returns the appropriate data based on the query parameter.

Output

When you enter a search term and submit the form, the browser navigates to a URL like:

				
					/search?query=term

				
			

Characteristics

  • Used for reading data.
  • Parameters are included in the URL (query string).
  • Data is visible in the URL, making it unsuitable for sensitive information.

POST Method

Basic Explanation

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.

Example

				
					<form action="/submit" method="POST">
  <label for="username">Username:</label>
  <input type="text" id="username" name="username">
  <label for="password">Password:</label>
  <input type="password" id="password" name="password">
  <input type="submit" value="Login">
</form>

				
			

Explanation

  • When the form is submitted, a POST request is made to the /submit endpoint, and the username and password fields are sent in the body of the request.
  • The server processes this data and can respond by creating a new user session or returning an error.

Output

Submitting this form sends the data securely to the server without including it in the URL.

Characteristics

  • Used for creating resources.
  • Data is sent in the request body, not visible in the URL.
  • Often used for sensitive or large amounts of data.

PUT Method

Basic Explanation

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.

Example

				
					fetch('/user/123', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    username: 'newUsername',
    email: 'newEmail@example.com'
  })
});

				
			

Explanation

  • In this example, a PUT request is sent to the /user/123 endpoint to update the user with ID 123 with new username and email data.
  • The server processes the request and updates the corresponding resource.

Characteristics

  • Used for updating or replacing an existing resource.
  • Idempotent: Repeated PUT requests with the same data will produce the same result.
  • The entire resource is usually replaced, not just parts of it.

DELETE Method

Basic Explanation

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.

Example

				
					fetch('/user/123', {
  method: 'DELETE'
});

				
			

Explanation

  • This example sends a DELETE request to remove the user with ID 123.
  • The server processes the request and deletes the user resource.

Characteristics

  • Used for deleting resources.
  • Idempotent: Repeated requests will have no additional effect after the resource is deleted.

PATCH Method

Basic Explanation

The PATCH method is used to partially update a resource. Unlike PUT, which replaces the entire resource, PATCH only updates the specified fields.

Example

				
					fetch('/user/123', {
  method: 'PATCH',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    email: 'newEmail@example.com'
  })
});

				
			

Explanation

  • In this example, a PATCH request is made to update only the email field of the user with ID 123.
  • The server processes the request and updates only the specified field.

Characteristics

  • Used for partial updates to a resource.
  • Not necessarily idempotent—repeated requests may not always result in the same state.

OPTIONS Method

Basic Explanation

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.

Example

				
					fetch('/resource', {
  method: 'OPTIONS'
});

				
			

Explanation

  • This request is made to check what methods are allowed for the /resource endpoint.

Characteristics

  • Used to describe communication options.
  • Commonly seen in preflight CORS requests.

HEAD Method

Basic Explanation

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.

Example

				
					fetch('/resource', {
  method: 'HEAD'
});

				
			

Explanation

  • This request retrieves the headers for the /resource endpoint without fetching the body.

Characteristics

  • Used to retrieve headers only.
  • Commonly used to check whether a resource exists or to retrieve metadata.

Idempotence and Safety in HTTP Methods

Safe Methods

  • A safe method is one that does not modify the resource on the server. The most notable safe method is GET.
  • Safe methods are read-only and should not cause any side effects.

Idempotent Methods

  • An idempotent method is one where making multiple identical requests will have the same effect as making a single request.
  • GET, PUT, DELETE, and HEAD are all idempotent methods, while POST and PATCH are not.

Advanced Concepts

CORS (Cross-Origin Resource Sharing)

  • CORS is a security feature implemented by browsers that restricts web pages from making requests to a domain different from the one that served the web page. For instance, a page loaded from example.com cannot make requests to another-site.com unless permitted by CORS.
  • Preflight requests use the OPTIONS method to check whether the cross-origin request is allowed.

REST and HTTP Methods

  • HTTP methods are heavily used in RESTful web services. In REST APIs, these methods map directly to CRUD (Create, Read, Update, Delete) operations:
    • GET: Read data
    • POST: Create data
    • PUT: Update or replace data
    • DELETE: Delete data
    • PATCH: Partially update data

HTTP Method Example: A Simple REST API

Here’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 !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India