Skip to content
All posts
API

Common HTTP Request Method

May 11, 2024·Read on Medium·

Common HTTP Request Method

HTTP methods that developers should know

Image by vectorjuice on Freepi

If you’re working on anything online, you’ll definitely come across HTTP request methods, whether you realize it or not. These methods are fundamental to web development, making the essential connections between the client and server possible. Let’s take a closer look at these methods, discuss possible weaknesses and talk about the best ways to handle them.

The GET method is used to obtain a resource from the server. It’s similar to requesting, “Hey, can you please provide me with this information?” Whenever you click on a link or enter a URL in your browser, you are using the GET method.

For instance, consider an API with a /customers endpoint. A GET request to this endpoint would typically retrieve a list of all the customers. Because of a GET request only shows data without altering any resources, it is regarded as both safe and idempotent in resource representation context.

Example Usage:

fetch('https://api.example.com/customers')
.then(response => response.json())
.then(data => console.log(data));

This is how the values handled by the target server:

GET /api/customers HTTP/1.1
Host: api.example.com

Best Practices

Since GET requests are meant to retrieve data without affecting server data, use them when you need to pull information. And yes, the backend are the one who control the request and what should do, so, making sure the backend are using the appropriate method validation for this practices. Also, because they’re cached by browsers, they’re great for improving loading speeds for unchanged resources.

Security Tips:

However, this is where most of the developers making a mistake where they are exposing sensitive information which falls under OWASP Top 10: Sensitive Data Exposure. Be cautious not to include sensitive data while retrieving data which leads to data breach, system information mass assignment and business disruption.

HTTP POST

POST method is commonly used (should be used) to create new or update resources. The HTTP POST method informs the server to alter the state of data of the target backend server. It’s like saying to the server, “Here’s some data, please store this for me.”

The POST method it is both not idempotent and not safe, meaning if you submit a form, if you hit send button twice, you’ll likely end up with two of the same resources since it mutates whatever data transmit on the backend server and change the resource state.

Example Usage:

fetch('https://api.example.com/customers/create', {
method: 'POST',
body: JSON.stringify({ name: 'John Doe', email: 'johndoe@email.com', password: 'Admin123'' }),
headers: { '
Content-Type': 'application/json' }
})
.then(response => response.json())
.then(data => console.log(data));

This is how the values handled by the target server:

POST /customers HTTP/1.1
Host: api.example.com
Content-Type: application/json

{
"name": "John Doe",
"email": "johndoe@email.com",
"password": "Admin123"
}

Best Practices

Since it is both not idempotent and not safe. Use POST method for only when creating new resources or any related operation that doesn’t involving altering data sources. Validate properly the content of the form and always store what are the features need without liberating the system security and functionality.

Security Tips

Don’t trust client input. Always validate and sanitize incoming data to prevent injections and other attacks. Ensure that sensitive operations via POST are protected by authentication mechanisms. Always use HTTPS to encrypt the data transmitted between the client and the server, protecting it from being intercepted or tampered with during transit.

HTTP PUT

PUT method is used to update a resource entirely. When using PUT, the client sends the complete updated entity, and this representation completely replaces the existing entity on the server. PUT requests are idempotent, meaning if you send the same PUT request multiple times, the result will be the same as sending it once.

Example Usage:

fetch('https://api.example.com/customers/1', {
method: 'PUT',
body: JSON.stringify({ name: 'Updated Item' }),
headers: { 'Content-Type': 'application/json' }
})
.then(response => response.json())
.then(data => console.log(data));

Best Practices

Use PUT when you have a resource that you want to modify or create if it doesn’t exist yet. Unlike POST, PUT is idempotent, which means sending the same request multiple times will not change the outcome after the initial request.

Security Tips

As with POST, always validate input to avoid SQL injection, XSS, and other injection attacks. Ensure that incoming data conforms to expected formats and values. Ensure that PUT requests are protected with appropriate authentication and authorization checks to prevent unauthorized access and modifications.

HTTP PATCH

PATCH is used for partial updates. Instead of sending a complete entity, PATCH requests only send the changes to the resource. This is more efficient when only a small portion of the resource needs updating. PATCH can be idempotent but is not necessarily so. It depends on the implementation—how the server processes the partial updates.

Example Usage:

fetch('https://api.example.com/data/1', {
method: 'PATCH',
body: JSON.stringify({ name: 'Partially Updated Item' }),
headers: { 'Content-Type': 'application/json' }
})
.then(response => response.json())
.then(data => console.log(data));

Best Practices

Yes, PATCH can theoretically be used to perform the same function as PUT by updating an entire resource, although this is not its typical use case. However, using PATCH in this way can lead to confusion and inconsistencies as the fundamental intent behind PATCH is to make partial updates. Always respect the semantic intent and do consistency across endpoints.

Security Tips

Just like PUT and POST, protect your PATCH requests with proper security measures. Only allow authenticated users to modify resources, and check that they have the necessary permissions to perform PUT or PATCH requests.

HTTP DELETE

DELETE method usually use to removes a resource specified by a URL It’s straightforward — like telling the server, “Please delete this information.”. Unlike POST, the DELETE is not safe and idempotent meaning that repeating the request multiple times should result in the same state (the resource remains deleted). It is because, DELETE requests do not carry data in the body. They usually specify the resource to be deleted in the URL.

Example Usage:

fetch('https://api.example.com/data/1', {
method: 'DELETE'
})
.then(() => console.log('Deleted successfully'));

Best Practices

Well, technically possible to configure a POST request to delete a resource on a server, it is not considered a best practice in web development. Following to the standard HTTP methods according to their intended uses is important for maintaining clear, understandable, and maintainable code.

Security Tips

Secure DELETE requests to ensure only authenticated users can perform deletions, and consider soft deletion strategies where applicable.

HTTP HEAD

What it does is HEAD method is essentially GET without the body. It’s used when you need the headers (like metadata) of a response without the actual data. Mostly the usage of HEAD method are caching, server health check and metadata retrieval.

Example Usage:

fetch('https://api.example.com/data', { 
method: 'HEAD'
}).then(response => console.log(response.headers.get('Content-Type')));

Best Practices

Use HEAD when you need to check what type of content is returned or whether a resource exists without downloading the entire content. Consider to differenciate the usage of GET and HEAD in your architecture.

Security Tips

As with GET, don’t expose any sensitive information.

HTTP OPTIONS

The OPTIONS method usually used to describe the communication options for a target resource. In simpler terms, it allows the client to find out what HTTP methods are supported by the server at any given URL. This can be particularly useful for dynamic web applications, where capabilities of a resource may vary. The most common usage is support cross-origin resource sharing (CORS) checking.

Example Usage:

fetch('https://api.example.com/resource', {
method: 'OPTIONS'
})
.then(response => response.headers.get('Allow'))
.then(allowedMethods => console.log('Allowed Methods:', allowedMethods));

Best Practices

Configure CORS settings on your server to handle OPTIONS requests appropriately, especially when allowing cross-origin requests. Ensure that the CORS policy is properly configured to prevent unauthorized access to sensitive resources.

Security Tips

While OPTIONS itself does not pose direct security risks since it does not involve data retrieval or modification, ensuring that CORS configurations are not overly permissive is crucial. Misconfigured CORS policies can expose the server to cross-site request forgery (CSRF) or other cross-origin attacks.

Wrapping Up

Different HTTP methods have different jobs in web development. Figuring out when and how to use them, keeping them safe from threats, and using best practices isn’t just about making things work — it’s about making sure your apps stay running well and secure. So, give these methods a try, play around with them and see how your web apps get better!

Found this helpful?

If this article saved you time or solved a problem, consider supporting — it helps keep the writing going.

Originally published on Medium.

View on Medium
Common HTTP Request Method — Hafiq Iqmal — Hafiq Iqmal