In this short snippet, you will learn how to make a PUT request with Axios to call an external API so let's get started.
What is Axios HTTP Client?
A little bit about
Axios, it is a promise-based HTTP client for the front-end applications and the node.js backend. It's a very simple and easy-to-use JavaScript library that many front-end applications depend on to call an external API.
How to install Axios?
To install Axios into your web application, you can use run any of the commands below.
npm install axios
yarn add axios
If you do prefer to use the CDN, you can just include the CDN below and you can right away make use of the library.
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
PUT Request in Axios Code Example
To perform a PUT request in Axios you can make use of the "put" method available from the "axios" object. Do note that this library is a promised-based library so it supports async/await syntax.<script>
import axios from 'axios';
const response = await axios
.put('https://jsonplaceholder.typicode.com/posts/1', {
id: 1,
title: 'foo',
body: 'bar',
userId: 1,
}, {
headers: { 'Content-type': 'application/json; charset=UTF-8' }
});
console.log(response);
</script>
In the case of the code example above, we will be using a fake API for testing from "jsonplaceholder.typicode.com" which is free to use. Below is the API endpoint that we'll be sending requests to with a PUT method.
https://jsonplaceholder.typicode.com/posts/1
Axios PUT Body Data
To specify the body data you can pass in an object of values as the second parameter like below.
const data = {
id: 1,
title: 'foo',
body: 'bar',
userId: 1,
}
axios.post('your-url-here', data);
Axios PUT Headers Configuration
To define header configuration for the PUT method, you can pass it in as the 3rd parameter. For any additional headers, you can pass it on as an object key and value pairs.
axios.post('your-url-here', 'your-data-here', {
headers: { 'Content-type': 'application/json; charset=UTF-8' }
});
Axios PUT with "then" method
To retrieve the response through the "then" keyword you can write your code like below.
axios
.post('your-url', 'your-data', 'your-headers')
.then((data) => console.log(data))
Leave a reply