102

I have gotten outside of GET and POST methods with Fetch. But I couldn't find any good DELETE and PUT example.

So, I ask you for it. Could you give a good example of DELETE and PUT methods with fetch. And explain it a little bit.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Kirill Stas
  • 1,359
  • 4
  • 12
  • 14

10 Answers10

78

Here is a fetch POST example. You can do the same for DELETE.

function createNewProfile(profile) {
    const formData = new FormData();
    formData.append('first_name', profile.firstName);
    formData.append('last_name', profile.lastName);
    formData.append('email', profile.email);

    return fetch('http://example.com/api/v1/registration', {
        method: 'POST',
        body: formData
    }).then(response => response.json())
}

createNewProfile(profile)
   .then((json) => {
       // handle success
    })
   .catch(error => error);
FlatLander
  • 1,717
  • 15
  • 21
  • 1
    So POST, PUT and DELETE are identical in syntax ? – Kirill Stas Oct 27 '16 at 12:22
  • 12
    The difference is that you will need the `id` of the record to DELETE or PUT. It will now look like `return fetch('http://example.com/api/v1/registration/1', {` `method: 'PUT',` `body: formData` `})` – Hanmaslah Jan 12 '17 at 12:02
  • Why do we need Id of the record if it is not needed for the API? – Sagar Mar 13 '20 at 05:48
  • 2
    'Needing an id' is specific to the API. The point that _is_ always true is that with `PUT` and `DELETE` you are updating or deleting the resource _at_ the URI respectively. So if do a `DELETE` request on `/x`, I expect `/x` to be deleted after. – Evert Nov 27 '20 at 07:30
69

Ok, here is a fetch DELETE example too:

fetch('https://example.com/delete-item/' + id, {
  method: 'DELETE',
})
.then(res => res.text()) // or res.json()
.then(res => console.log(res))
Damjan Pavlica
  • 31,277
  • 10
  • 71
  • 76
30

For put method we have:

const putMethod = {
 method: 'PUT', // Method itself
 headers: {
  'Content-type': 'application/json; charset=UTF-8' // Indicates the content 
 },
 body: JSON.stringify(someData) // We send data in JSON format
}

// make the HTTP put request using fetch api
fetch(url, putMethod)
.then(response => response.json())
.then(data => console.log(data)) // Manipulate the data retrieved back, if we want to do something with it
.catch(err => console.log(err)) // Do something with the error

Example for someData, we can have some input fields or whatever you need:

const someData = {
 title: document.querySelector(TitleInput).value,
 body: document.querySelector(BodyInput).value
}

And in our data base will have this in json format:

{
 "posts": [
   "id": 1,
   "title": "Some Title", // what we typed in the title input field
   "body": "Some Body", // what we typed in the body input field
 ]
}

For delete method we have:

const deleteMethod = {
 method: 'DELETE', // Method itself
 headers: {
  'Content-type': 'application/json; charset=UTF-8' // Indicates the content 
 },
 // No need to have body, because we don't send nothing to the server.
}
// Make the HTTP Delete call using fetch api
fetch(url, deleteMethod) 
.then(response => response.json())
.then(data => console.log(data)) // Manipulate the data retrieved back, if we want to do something with it
.catch(err => console.log(err)) // Do something with the error

In the url we need to type the id of the of deletion: https://www.someapi/id

Community
  • 1
  • 1
Grecdev
  • 899
  • 9
  • 14
9

Just Simple Answer. FETCH DELETE

function deleteData(item, url) {
  return fetch(url + '/' + item, {
    method: 'delete'
  })
  .then(response => response.json());
}
user3335966
  • 2,673
  • 4
  • 30
  • 33
Mr Fun
  • 331
  • 3
  • 11
6

Here is good example of the CRUD operation using fetch API:

“A practical ES6 guide on how to perform HTTP requests using the Fetch API” by Dler Ari https://link.medium.com/4ZvwCordCW

Here is the sample code I tried for PATCH or PUT

function update(id, data){
  fetch(apiUrl + "/" + id, {
    method: 'PATCH',
    body: JSON.stringify({
     data
    })
  }).then((response) => {
    response.json().then((response) => {
      console.log(response);
    })
  }).catch(err => {
    console.error(err)
  })

For DELETE:

function remove(id){
  fetch(apiUrl + "/" + id, {
    method: 'DELETE'
  }).then(() => {
     console.log('removed');
  }).catch(err => {
    console.error(err)
  });

For more info visit Using Fetch - Web APIs | MDN https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch > Fetch_API.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Murtaza Hussain
  • 3,851
  • 24
  • 30
  • 1
    Remember we're trying to write reference-quality content here; you shouldn't be adding "thanks" to everything, and definitely not emoji (unless the Q&A is actually about dealing with them, e.g. Unicode handling). – jonrsharpe May 12 '19 at 06:58
6

Some examples:

async function loadItems() {
        try {
            let response = await fetch(`https://url/${AppID}`);
            let result = await response.json();
            return result;
        } catch (err) {
        }
    }

    async function addItem(item) {
        try {
            let response = await fetch("https://url", {
                method: "POST",
                body: JSON.stringify({
                    AppId: appId,
                    Key: item,
                    Value: item,
                    someBoolean: false,
                }),
                headers: {
                    "Content-Type": "application/json",
                },
            });
            let result = await response.json();
            return result;
        } catch (err) {
        }
    }

    async function removeItem(id) {
        try {
            let response = await fetch(`https://url/${id}`, {
                method: "DELETE",
            });
        } catch (err) {
        }
    }

    async function updateItem(item) {
        try {
            let response = await fetch(`https://url/${item.id}`, {
                method: "PUT",
                body: JSON.stringify(todo),
                headers: {
                    "Content-Type": "application/json",
                },
            });
        } catch (err) {
        }
    }
Bogdan M.
  • 2,161
  • 6
  • 31
  • 53
Ven
  • 61
  • 1
  • 2
  • mmm... really??? this doesn't make sense... why do you send the ID in the url and the rest of the data in the body? I've never seen such a PUT hit... – Ari Waisberg Apr 11 '21 at 22:38
4

Let me simplify this, you can straight up copy the code.

This is for PUT method :

fetch('https://reqres.in/api/users', + id {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'user'
  })
})
.then(res => {
  return res.json()
})
.then(data => console.log(data))

and this is for DELETE :

fetch('https://reqres.in/api/users' + id, {
  method: 'DELETE',
})
.then(res => {
  return res.json()
}) 
.then(data => console.log(data))

Note: I'm using dummy api here.

Suraj
  • 802
  • 9
  • 7
3

This is what worked for me when using the PUT method. This method allows me to effectively update the 1st item using my first name:

fetch('https://reqres.in/api/users', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    id: 1,
    first_name: 'Anthony'
  })
})
.then(res => {
  return res.json()
})
.then(data => console.log(data))
1

Here are examples for Delete and Put for React & redux & ReduxThunk with Firebase:

Update (PUT):

export const updateProduct = (id, title, description, imageUrl) => {
    await fetch(`https://FirebaseProjectName.firebaseio.com/products/${id}.json`, {
  method: "PATCH",
  header: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    title,
    description,
    imageUrl,
  }),
});

dispatch({
  type: "UPDATE_PRODUCT",
  pid: id,
  productData: {
    title,
    description,
    imageUrl,
  },
});
};
};

Delete:

export const deleteProduct = (ProductId) => {
  return async (dispatch) => {
await fetch(
  `https://FirebaseProjectName.firebaseio.com/products/${ProductId}.json`,
  {
    method: "DELETE",
  }
);
dispatch({
  type: "DELETE_PRODUCT",
  pid: ProductId,
});
  };
};
Ori
  • 160
  • 1
  • 10
0
const DeleteBtn = (id) => {

    fetch(`http://localhost:8000/blogs/${id}`, {
        method: "DELETE"
    })
        .then(() => {
            navigate('/');
        });

}
<button onClick={(event) => { DeleteBtn(blog.id)} }>delete</button>
cigien
  • 57,834
  • 11
  • 73
  • 112