HTTP Methods Reference

Overview

HTTP methods, also known as HTTP verbs, define the type of action to be performed on a resource when making HTTP requests. Understanding these methods is fundamental to building web applications that interact with servers, APIs, and databases. Each method has specific semantics that indicate the intended operation, and using the correct method ensures your application follows RESTful principles and behaves predictably.

This reference guide covers the most commonly used HTTP methods, their purposes, characteristics, and practical usage scenarios. Whether you are building a REST API, consuming third-party services, or implementing form submissions, knowing when to use each HTTP method is essential for creating well-designed web applications.

HTTP methods reference diagram

When to Use HTTP Methods

HTTP methods should be selected based on the operation you intend to perform. Reading data uses different methods than creating, updating, or deleting data. Following these conventions makes your API intuitive and allows clients to understand the expected behavior without detailed documentation. Additionally, proper use of HTTP methods enables features like caching, idempotency, and safe operations.

How HTTP Methods Work

When a client makes an HTTP request, it specifies a method along with the target URL, headers, and optionally a request body. The server receives this request, processes it according to the method semantics, and returns an appropriate response with a status code indicating the result. The method tells the server what kind of operation the client wants to perform on the specified resource.

GET Method

Parameters and Options

The GET method requests data from a specified resource. It should only retrieve data and have no other effect on the resource. GET requests can include query parameters in the URL to filter or specify what data to retrieve.

fetch('https://api.example.com/users?role=admin&status=active')

Key characteristics of GET:

Example Usage

async function getUser(userId) {
    const response = await fetch(`https://api.example.com/users/${userId}`);
    
    if (!response.ok) {
        throw new Error(`Failed to fetch user: ${response.status}`);
    }
    
    const user = await response.json();
    return user;
}

Common Pitfalls

Never use GET for operations that change server state. While it may work technically, it violates HTTP semantics and creates security risks. Search engines and browsers may pre-fetch GET URLs, potentially triggering unintended actions. Use POST, PUT, or DELETE for state-changing operations.

POST Method

Parameters and Options

The POST method submits data to be processed to a specified resource. It is typically used to create new resources or submit form data. POST requests include data in the request body rather than the URL.

fetch('https://api.example.com/users', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        name: 'John Doe',
        email: '[email protected]'
    })
})

Key characteristics of POST:

Example Usage

async function createUser(userData) {
    const response = await fetch('https://api.example.com/users', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer token123'
        },
        body: JSON.stringify(userData)
    });
    
    if (!response.ok) {
        const error = await response.json();
        throw new Error(error.message);
    }
    
    const createdUser = await response.json();
    return createdUser;
}

Common Pitfalls

Submitting forms with GET when POST is appropriate exposes sensitive data in URLs and browser history. Always use POST for operations that create resources or send sensitive information. Additionally, POST requests that fail due to network issues may result in duplicate resources if retried without proper handling.

PUT Method

Parameters and Options

The PUT method replaces the entire resource at the specified URL with the data provided in the request body. If the resource does not exist, PUT may create it.

fetch('https://api.example.com/users/123', {
    method: 'PUT',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        id: 123,
        name: 'John Doe',
        email: '[email protected]',
        role: 'admin'
    })
})

Key characteristics of PUT:

Example Usage

async function updateUser(userId, userData) {
    const response = await fetch(`https://api.example.com/users/${userId}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(userData)
    });
    
    if (!response.ok) {
        throw new Error(`Failed to update user: ${response.status}`);
    }
    
    return await response.json();
}

Common Pitfalls

Using PUT for partial updates is incorrect and can unintentionally delete fields not included in the request body. Use PATCH for partial updates instead. Also, ensure PUT requests include all required fields for the resource to maintain data integrity.

DELETE Method

Parameters and Options

The DELETE method removes the specified resource from the server.

fetch('https://api.example.com/users/123', {
    method: 'DELETE'
})

Key characteristics of DELETE:

Example Usage

async function deleteUser(userId) {
    const response = await fetch(`https://api.example.com/users/${userId}`, {
        method: 'DELETE',
        headers: {
            'Authorization': 'Bearer token123'
        }
    });
    
    if (!response.ok) {
        throw new Error(`Failed to delete user: ${response.status}`);
    }
    
    return true;
}

Common Pitfalls

Implementing delete operations without proper authorization checks can lead to security vulnerabilities. Always verify that the user has permission to delete the resource. Additionally, consider implementing soft deletes for important data rather than permanent deletion to enable recovery.

PATCH Method

Parameters and Options

The PATCH method applies partial modifications to a resource. Unlike PUT, PATCH only updates the fields provided in the request body.

fetch('https://api.example.com/users/123', {
    method: 'PATCH',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        email: '[email protected]'
    })
})

Key characteristics of PATCH:

Example Usage

async function updateUserEmail(userId, newEmail) {
    const response = await fetch(`https://api.example.com/users/${userId}`, {
        method: 'PATCH',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            email: newEmail
        })
    });
    
    if (!response.ok) {
        throw new Error(`Failed to update email: ${response.status}`);
    }
    
    return await response.json();
}

Best Practices

When working with HTTP methods, follow these best practices to create robust and maintainable applications:

Conclusion

Understanding HTTP methods is essential for building web applications that communicate effectively with servers and APIs. Each method has distinct semantics and use cases that guide how clients and servers interact. By using the appropriate method for each operation, you create applications that are predictable, maintainable, and follow established web standards.

Remember that GET is for reading, POST for creating, PUT for replacing, PATCH for updating, and DELETE for removing. These methods form the foundation of RESTful API design and enable clients to perform all necessary operations on server resources. As you build web applications, always consider which HTTP method best represents the action you want to perform, and implement proper error handling and security measures for all state-changing operations.