Sending PUT HTTP Requests with Axios

Introduction

Axios is a JavaScript library for making HTTP requests, either in the browser or Node.js.

Unlike the popular Requests library, Axios is natively promise-based, making it more suitable for modern applications taking advantage of newer JavaScript features, like Promises and the async/await syntax.

If you're experienced in web development and would just like to find an answer as to how to send a PUT request with Axios - the long story short is:

const axios = require('axios');

// Wrapper, specific put() function
const res = await axios.put('/api/article/123', {
    title: 'Making PUT Requests with Axios',
    status: 'published'
});

// General HTTP function
const res = await axios({
    method: 'put',
    url: '/api/article/123',
    data: {
        title: 'Making PUT Requests with Axios',
        status: 'published'
    }
});

However, if you're new to working with Axios or would like to know more about how this works - read on!

HTTP Requests and Verbs

The modern web is built on the HTTP protocol and a request-response lifecycle, where a client requests a resource, and a server responds with it.

The HTTP protocol defines a number of methods with varying intentions, namely GET, POST, DELETE, etc. which allow a client to "state" their intention. One of the more common HTTP methods is the PUT method, which is most commonly used for sending data to a server, either for creating a new resource or for patching or editing data on an existing resource.

For instance, a REST API service for a blog may have a route that allows you to perform CRUD (Create, Read, Update, Delete) operations on the article resource using the path /api/article/[id].

Sending a GET request to this route might return the article specified by the id. Sending a PUT request to this path would edit the specified attributes article. These attributes can be specified in the body of the request, which is serialized to JSON format by default.

If you'd like to read more about creating REST APIs with Node.js - read our Guide to Building a REST API with Node and Express!

Sending a PUT Request with Axios

Let's see how we can use the Axios library to send an HTTP PUT request from your JavaScript application.

First, you can install axios using yarn or npm:

$ npm install axios --save
$ yarn add axios

It's also available for frontend applications via a number of CDNs, such as jsDelivr:

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

Once the library is installed, you'll need to instantiate an instance:

const axios = require('axios');

The simplest way to make the PUT call is to simply use the put() function of the axios instance, and supply the body of that request in the form of a JavaScript object:

const res = await axios.put('/api/article/123', {
    title: 'Making PUT Requests with Axios',
    status: 'published'
});

The only arguments needed here are the URL and the data you wish to send, which in our case is the title in which we want to edit the article resource.

The JavaScript object we've created to hold the title and status is serialized into JSON, sent to a request handler, which performs an action and returns a result. The body of the request we're sending is the serialized JSON, which can easily be retrieved on the back-end.

Note: Since JSON is being sent - which is a very universal format, most frameworks will have no issues reading the sent data and deserializing it into whatever representation the back-end uses, regardless of the tech stack.

The object returned by Axios, res in this case, has a standard schema for all calls:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

{
    data: {},
    status: 200,
    statusText: 'OK',
    headers: {},
    config: {},
    request: {}
}

Where:

  • data: The data returned by the service you called - typically, a JSON response from a REST API.
  • status: The HTTP status returned by the service, denoting how the operation went - like 200 (OK), 301 (Moved Permanently), 404 (Not Found), etc.
  • statusText: The HTTP status text describing the status code in a human-readable format - like 'OK', 'Moved Permanently', or 'Not Found'.
  • headers: An object containing all headers returned by the service, like 'Cache-Control'.
  • config: The config object provided to the call (optional).
  • request: The request object for this call, which is a ClientRequest in Node.js or XMLHttpRequest in the browser.

Another way to make a PUT request with Axios is a more generic method in which you specify the HTTP method within the arguments.

This is done by using the axios() default method and config object:

const res = await axios({
    method: 'put',
    url: '/api/article/123',
    data: {
        title: 'Making PUT Requests with Axios',
        status: 'published'
    }
});

The result of this call is exactly the same as the axios.put() call from earlier - the only difference being that the axios.put() method is a convenience method that wraps the general method, imbuing it with the method: 'put' field.

axios() vs put()

So why would you use one method over the other? That may depend on a few factors, like readability or the context in which the method is used, but also to a large degree - your personal preference.

The more generic axios() call is more flexible since all options/configs are specified within the same object, making it easier to add more configs, like headers for example, or switching method verbs.

Since the put() method just wraps axios(), the underlying functionality is fundamentally the same.

Handling Errors

Note: When sending requests - you might not always get an expected result back.

Generally speaking - you'll want to try sending a request, and catch exceptions if they arise in that process, which changes the call procedure a tiny bit:

try {
    const { data } = await axios({
        method: 'put',
        url: '/api/article/123',
        data: {
            title: 'Making PUT Requests with Axios',
            status: 'published'
        }
    });

    console.log(data);
} catch (err) {
    if (err.response.status === 404) {
        console.log('Resource could not be found!');
    } else {
        console.log(err.message);
    }
}

The main difference here is the error handling, which uses the response object within the error to determine the cause rather than the data object returned from the call itself.

Typically, error-handling is more robust than just checking whether the status is a single integer - however, this way you can alter the flow of the logic based on how the request was handled (or wasn't).

Conclusion

In this article we gave a short introduction to the Axios library and the HTTP PUT method.

We also showed a few examples of how Axios can be used to make PUT calls, as well as how other configurations can be called and how simple errors can be handled.

Last Updated: May 12th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Project

React State Management with Redux and Redux-Toolkit

# javascript# React

Coordinating state and keeping components in sync can be tricky. If components rely on the same data but do not communicate with each other when...

David Landup
Uchechukwu Azubuko
Details

Getting Started with AWS in Node.js

Build the foundation you'll need to provision, deploy, and run Node.js applications in the AWS cloud. Learn Lambda, EC2, S3, SQS, and more!

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms