Fetch and HTTP Methods
You'll learn how to tell the server exactly what action you want—retrieving data, creating resources, updating, or deleting—using HTTP methods with the Fetch API.
Why HTTP Methods Matter
When you communicate with a server, the method specifies your intention. Think of it like verbs in a sentence: GET means "give me data," POST means "create something new," PUT means "update this," and DELETE means "remove this." By default, fetch() uses GET, but real-world applications need all these actions.
Specifying Methods via Options
The second argument to fetch() is an options object where you declare the HTTP method:
// Default GET (explicitly shown)
fetch('https://api.example.com/users', {
method: 'GET'
});
// POST to create a new user
fetch('https://api.example.com/users', {
method: 'POST',
body: JSON.stringify({ name: 'Alice' }),
headers: { 'Content-Type': 'application/json' }
});
// PUT to update user with ID 42
fetch('https://api.example.com/users/42', {
method: 'PUT',
body: JSON.stringify({ name: 'Alice Updated' }),
headers: { 'Content-Type': 'application/json' }
});
// DELETE to remove user 42
fetch('https://api.example.com/users/42', {
method: 'DELETE'
});
Notice how POST and PUT typically include a body (the data you're sending) and headers to tell the server what format you're using. DELETE and GET usually don't send bodies.
Other Methods
You might also encounter PATCH (partial updates), HEAD (like GET but only retrieves headers), or OPTIONS (asks what methods are allowed). The pattern remains the same: specify method in the options object.
Key Takeaway: Control what you're asking the server to do by setting the method property in fetch's options object—GET retrieves, POST creates, PUT updates, DELETE removes.