For this example, we will be using "{JSON} Placeholder" which is a "Free fake API for testing and prototyping".
https://jsonplaceholder.typicode.com
Fetch API update Resource
The code below updates the post with the ID of 1 to have "foo" as the title and "bar" as the body value and assigned to the user with an ID of 1. The "fetch" function accepts URL as the 1st parameter and the 2nd-second parameter is an object. Do note that the headers are also specified.
fetch('https://jsonplaceholder.typicode.com/posts/1', { method: 'PUT', body: JSON.stringify({ id: 1, title: 'foo', body: 'bar', userId: 1, }), headers: { 'Content-type': 'application/json; charset=UTF-8', }, }) .then((response) => response.json()) .then((json) => console.log(json));
{ id: 1, title: 'foo', body: 'bar', userId: 1 }
Leave a reply