Ever wondered why sometimes you use GET in your API calls and other times POST? Understanding HTTP request methods (also called HTTP verbs) is fundamental to building robust REST APIs and web applications. These methods define the intended action for a given resource, forming the backbone of client-server communication.
In this guide, we'll demystify the core HTTP methods—GET, POST, PUT, PATCH, and DELETE—along with their practical applications in Node.js and modern JavaScript.
Meta Context: This comprehensive guide covers HTTP request methods including GET vs POST comparisons, idempotent operations, safe methods, and practical examples for REST API design and CRUD operations using Node.js and the fetch API.
What Are HTTP Methods?
HTTP methods specify the desired action to perform on a resource identified by a URL. Think of them as verbs in a sentence—they tell the server what you want to do with the resource.
Each method has specific characteristics:
- Safe methods: Read-only operations that don't modify server state
- Idempotent methods: Produce the same result regardless of how many times they're executed
- CRUD operations: Methods map to Create, Read, Update, Delete actions
GET: Retrieving Data
GET is the most common HTTP method used to retrieve data from a server. It's both safe and idempotent—multiple identical requests produce the same result without side effects.
Key Characteristics:
- Should never modify server data
- Parameters sent in URL query strings
- Cacheable by browsers and proxies
- Can be bookmarked
// Frontend: Fetching user data
const response = await fetch('https://api.example.com/users/123');
const user = await response.json();
console.log(user);
// Backend: Handling GET request (Express)
import express from 'express';
const app = express();
app.get('/users/:id', (req, res) => {
const userId = req.params.id;
// Fetch from database
res.json({ id: userId, name: 'John Doe' });
});
POST: Creating Resources
POST creates new resources on the server. It's not idempotent—multiple identical requests can create multiple resources.
Key Characteristics:
- Used for creating new records
- Data sent in request body
- Not cacheable by default
- Returns HTTP status code 201 (Created) on success
// Frontend: Creating a new user
const newUser = { name: 'Jane', email: 'jane@example.com' };
const response = await fetch('https://api.example.com/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(newUser)
});
// Backend: Handling POST request
app.post('/users', (req, res) => {
const userData = req.body;
// Save to database and return created resource
res.status(201).json({ id: 'new-id', ...userData });
});
PUT: Replacing Resources
PUT completely replaces an existing resource. It's idempotent—sending the same PUT request multiple times produces identical results.
Key Characteristics:
- Replaces entire resource
- Requires full resource representation
- Creates resource if it doesn't exist (sometimes)
- Idempotent nature makes it safe for retries
// Frontend: Replacing user data
const updatedUser = { name: 'Jane Smith', email: 'jane.smith@example.com' };
await fetch('https://api.example.com/users/123', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(updatedUser)
});
// Backend: Handling PUT request
app.put('/users/:id', (req, res) => {
const userId = req.params.id;
// Replace entire user document
res.json({ id: userId, ...req.body });
});
PATCH: Partial Updates
PATCH applies partial modifications to a resource. Unlike PUT, you only send the fields you want to change.
Key Characteristics:
- Updates specific fields only
- More efficient than PUT for small changes
- Idempotent (though technically optional per spec)
- Perfect for updating single properties
// Frontend: Updating only email
const partialUpdate = { email: 'newemail@example.com' };
await fetch('https://api.example.com/users/123', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(partialUpdate)
});
// Backend: Handling PATCH request
app.patch('/users/:id', (req, res) => {
const userId = req.params.id;
// Merge changes with existing data
res.json({ id: userId, ...req.body });
});
DELETE: Removing Resources
DELETE removes a resource from the server. It's idempotent—deleting the same resource multiple times results in the same state (resource doesn't exist).
Key Characteristics:
- Removes specified resource
- Returns 204 (No Content) or 200 with confirmation
- Subsequent DELETE requests typically return 404
// Frontend: Deleting a user
await fetch('https://api.example.com/users/123', {
method: 'DELETE'
});
// Backend: Handling DELETE request
app.delete('/users/:id', (req, res) => {
const userId = req.params.id;
// Remove from database
res.status(204).send();
});
Other Important Methods
HEAD: Identical to GET but returns only headers, no body. Useful for checking resource existence or metadata.
OPTIONS: Returns supported HTTP methods for a resource. Essential for CORS preflight requests.
// Backend: Handling OPTIONS for CORS
app.options('/users', (req, res) => {
res.header('Allow', 'GET, POST, PUT, DELETE');
res.send();
});
GET vs POST: Key Differences
| Aspect | GET | POST |
|---|---|---|
| Purpose | Retrieve data | Create/submit data |
| Data Location | URL parameters | Request body |
| Idempotent | Yes | No |
| Cacheable | Yes | No |
| Bookmarkable | Yes | No |
PUT vs PATCH: When to Use Which?
Use PUT when replacing an entire resource with complete new data. Use PATCH when updating specific fields without affecting others. PATCH is more bandwidth-efficient for minor updates.
Summary: Building Better APIs
Understanding HTTP methods is crucial for effective REST API design. Remember:
- Use GET for safe, read-only operations
- Use POST for creating new resources
- Choose PUT for full replacements, PATCH for partial updates
- Apply DELETE for resource removal
- Respect idempotency and safety characteristics for reliable APIs
Master these fundamentals, and you'll build more predictable, maintainable, and standards-compliant web applications. Start applying these patterns in your next Node.js project, and your API consumers will thank you.
Top comments (0)