Axios Tutorial: Get/Post/Put/Delete Request example
Tags: todayilearned, webdev, javascript, axios
Published: 2021-08-03 08:58:33

Axios is a promise-based HTTP Client Javascript library for Node.js and Browser. In this tutorial, we will create examples that use Axios to make Get/Post/Put/Delete request. The final section shows a simple Axios HTTP Client to interact with Rest API.

Related Post:
- <a href="https://www.bezkoder.com/axios-interceptors-refresh-token/">Axios Interceptors tutorial with Refresh Token example</a>
- [Axios File upload](https://www.bezkoder.com/axios-file-upload/)

Article from [BezKoder](https://www.bezkoder.com/axios-request/)

<!--more-->
<h2>Axios Features</h2>
Axios can run in the Node.js and Browser with the same codebase.
- On the server-side it uses the native Node.js <code>http</code> module
- On the client-side (browser) it uses <code>XMLHttpRequests</code>

Additionally, there are important features that you should know:
<ul>
	<li>Supports the Promise API</li>
	<li>Intercept request and response (<a href="https://www.bezkoder.com/axios-interceptors-refresh-token/">Axios Interceptors tutorial</a>)</li>
	<li>Transform request and response data</li>
	<li>Cancel requests</li>
	<li>Automatic transforms for JSON data</li>
	<li>Client side support for protecting against XSRF</li>
</ul>
(from <a href="https://github.com/axios/axios#features">https://github.com/axios/axios#features</a>)

<h2>Install Axios</h2>
We can add Axios to our project/code with one of following simple ways:

- npm:
```bash
npm install axios
```

- bower:
```bash
bower install axios
```

- yarn:
```bash
yarn add axios
```

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

Or:
```html
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
```

<h2>Axios Response Object schema</h2>
The response for a Axios request contains:
<ul>
	<li><code>data</code>: parsed response body provided by the server</li>
	<li><code>status</code>: HTTP status code</li>
	<li><code>statusText</code>: HTTP status message</li>
	<li><code>headers</code>: HTTP headers (lower case)</li>
	<li><code>config</code>: the request config that was provided to <code>axios</code></li>
	<li><code>request</code>: the last client request instance that generated this response</li>
</ul>

For example:
```json
{
  "data": {
    "id": 1,
    "title": "Axios Request",
    "description": "Tut#1 Description",
    "published": true
  },
  "status": 200,
  "statusText": "OK",
  "headers": {
    "content-length": "162",
    "content-type": "application/json; charset=utf-8"
  },
  "config": {
    "url": "/tutorials/1",
    "method": "get",
    "headers": {
      "Accept": "application/json, text/plain, */*"
    },
    "baseURL": "http://localhost:8080/api",
    "transformRequest": [
      null
    ],
    "transformResponse": [
      null
    ],
    "timeout": 0,
    "xsrfCookieName": "XSRF-TOKEN",
    "xsrfHeaderName": "X-XSRF-TOKEN",
    "maxContentLength": -1,
    "maxBodyLength": -1
  }
}
```

<h2>Axios Response Body</h2>
Axios Response Object has <code>data</code> field that contains the parsed response body.
We can use <code>then</code> or await to receive the response body as follows:

```js
axios.get('/bezkoder.com/tutorials')
  .then(function (response) {
    console.log(response.data);
  });

const { data } = await axios.get(url);
```

<h2>Axios Error handling</h2>
We use <code>catch()</code> for handling errors.

```js
axios.get('/bezkoder.com/tutorials')
  .then(...)
  .catch(function (error) {
    if (error.response) { // get response with a status code not in range 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) { // no response
      console.log(error.request);
      // instance of XMLHttpRequest in the browser
      // instance ofhttp.ClientRequest in node.js
    } else { // Something wrong in setting up the request
      console.log('Error', error.message);
    }
    console.log(error.config);
  });
```

<h2>Axios Error handling with async-await</h2>
If you want to use async-await, just wrap the axios call with try/catch block.

```js
async function getTutorial() {
  try {
    const response = await axios.get('/bezkoder.com/tutorials');
    console.log(response);
  } catch (error) {
    if (error.response) { // get response with a status code not in range 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) { // no response
      console.log(error.request);
    } else { // Something wrong in setting up the request
      console.log('Error', error.message);
    }
    console.log(error.config);
  }
}
```

<h2>Axios GET request</h2>

```js
axios.get('/bezkoder.com/tutorials')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });
```

Async/await:
```js
async function getTutorial() {
  try {
    const response = await axios.get('/bezkoder.com/tutorials');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}
```

<h2>Axios GET with params</h2>
You can use the <code>params</code> config option to set query string params.
```js
axios.get(
  '/bezkoder.com/tutorials',
  {
    params: {
      title: 'ios'
    }
  }
);
```

And this is equivalent:
```js
axios.get('/tutorials?title=ios');
```

<h2>Axios GET with headers</h2>
To send Axios GET request with Headers, we pass an option object with <code>headers</code> property.

```js
axios.get(
  '/bezkoder.com/tutorials',
  {
    headers: {
      'x-access-token': 'token-value'
    }
  }
);
```

<h2>Axios GET with params and headers</h2>
We can merge <code>params</code> and <code>headers</code> in a Axios GET request like this.

```js
axios.get(
  '/bezkoder.com/tutorials',
  {
    params: {
      title: 'ios'
    },
    headers: {
      'x-access-token': 'token-value'
    }
  }
);
```

<h2>Axios POST with body</h2>
You can perform an Axios POST object request with <code>body</code> as second parameter.

```js
axios.post(
  '/bezkoder.com/tutorials',
  {
    title: title,
    description: description,
  }
);
```

<h2>Axios POST with headers</h2>
To send Axios POST request with Headers, we pass an option object with <code>headers</code> property right after the <code>body</code>.

```js
await axios.post(
  '/bezkoder.com/tutorials',
  {
    title: title,
    description: description,
  },
  {
    headers: {
      "x-access-token": "token-value",
    },
  }
);
```

<h2>Axios PUT request</h2>
You can perform an Axios PUT json object request with <code>body</code> as second parameter.

```js
axios.put(
  '/bezkoder.com/tutorials/42',
  {
    title: title,
    description: description,
    published: true,
  }
);
```

<h2>Axios PUT with headers</h2>
To send Axios PUT request with Headers, we pass an option object with <code>headers</code> property right after the <code>body</code>.

```js
axios.put(
  '/bezkoder.com/tutorials/42',
  {
    title: title,
    description: description,
    published: true,
  },
  {
    headers: {
      "x-access-token": "token-value",
    },
  }
);
```

<h2>Axios DELETE request</h2>

```js
axios.delete('/bezkoder.com/tutorials/42');
```

<h2>Axios DELETE with headers</h2>
To send Axios DELETE request with Headers, we pass an option object with <code>headers</code> property.

```js
axios.delete(
  '/bezkoder.com/tutorials/42',
  {
    headers: {
      "x-access-token": "token-value",
    },
  }
);
```

<h2>Create Axios instance</h2>
We can create a new instance of axios using <code>axios.create(config)</code> method.

```js

const instance = axios.create({
  baseURL: 'https://bezkoder.com/api/',
  timeout: 2000,
  headers: {'X-Custom-Header': 'bezkoder'}
});
```

<h2>Axios Request example with Rest API</h2>
We will build a HTTP Client to make CRUD requests to Rest API in that:
<ul>
	<li>Axios GET request: get all Tutorials, get Tutorial by Id, find Tutorial by title</li>
	<li>Axios POST request: create new Tutorial</li>
	<li>Axios PUT request: update an existing Tutorial</li>
	<li>Axios DELETE request: delete a Tutorial, delete all Tutorials</li>
</ul>

![axios-request-example-get-post-put-delete](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l5nefjtjcvm5v92r5hin.png)

This Axios Client works with the following Web API:
<div class="table-responsive">
<table class="table table-hover  table table-hover" width="100%">
<thead>
<tr>
<th>Methods</th>
<th>Urls</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>POST</td>
<td>/api/tutorials</td>
<td>create new Tutorial</td>
</tr>
<tr>
<td>GET</td>
<td>/api/tutorials</td>
<td>retrieve all Tutorials</td>
</tr>
<tr>
<td>GET</td>
<td>/api/tutorials/:id</td>
<td>retrieve a Tutorial by <code>:id</code></td>
</tr>
<tr>
<td>PUT</td>
<td>/api/tutorials/:id</td>
<td>update a Tutorial by <code>:id</code></td>
</tr>
<tr>
<td>DELETE</td>
<td>/api/tutorials/:id</td>
<td>delete a Tutorial by <code>:id</code></td>
</tr>
<tr>
<td>DELETE</td>
<td>/api/tutorials</td>
<td>delete all Tutorials</td>
</tr>
<tr>
<td>GET</td>
<td>/api/tutorials?title=[keyword]</td>
<td>find all Tutorials which title contains <code>keyword</code></td>
</tr>
</tbody>
</table>
</div>

You can find step by step to build a Server like this in one of these posts:
<ul>
	<li><a href="https://bezkoder.com/node-js-express-sequelize-mysql/">Express, Sequelize & MySQL</a></li>
	<li><a href="https://bezkoder.com/node-express-sequelize-postgresql/">Express, Sequelize & PostgreSQL</a></li>
	<li><a href="https://bezkoder.com/node-express-mongodb-crud-rest-api/">Express & MongoDb</a></li>
	<li><a href="https://bezkoder.com/spring-boot-jpa-crud-rest-api">Spring Boot & MySQL</a></li>
	<li><a href="https://bezkoder.com/spring-boot-postgresql-example/">Spring Boot & PostgreSQL</a></li>
	<li><a href="https://bezkoder.com/spring-boot-mongodb-crud/">Spring Boot & MongoDB</a></li>
	<li><a href="https://bezkoder.com/spring-boot-jpa-h2-example/">Spring Boot & H2</a></li>
	<li><a href="https://bezkoder.com/spring-boot-cassandra-crud/">Spring Boot & Cassandra</a></li>
	<li><a href="https://bezkoder.com/spring-boot-hibernate-oracle/">Spring Boot & Oracle</a></li>
	<li><a href="https://bezkoder.com/django-crud-mysql-rest-framework/">Django & MySQL</a></li>
	<li><a href="https://bezkoder.com/django-postgresql-crud-rest-framework/">Django & PostgreSQL</a></li>
	<li><a href="https://bezkoder.com/django-mongodb-crud-rest-framework/">Django & MongoDB</a></li>
</ul>

<div class="alert alert-warning">
Remember that you need to configure CORS: <code>Access-Control-Allow-Origin: *</code>.
It helps the REST APIs can be accessed by <strong>any</strong> origin.
</div>

- Create a Tutorial using axios POST request:

![axios-post-request-example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1eu8damg1qy6zkwglahd.png)

- Retrieve all Tutorials using axios GET request:

![axios-get-request-example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k4axque7ur334z8tl5zg.png)

- Retrieve a Tutorial by Id using axios GET request:

![axios-get-request-example-by-id](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oa3s1l60thiuqpqifx58.png)

- Find Tutorials by title using axios GET request with params:

![axios-get-request-params-example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7jaw49tqlq1bmub3zmd7.png)

- Update a Tutorial using axios PUT request:

![axios-put-request-example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6grr9g6ln3a14ipg27gr.png)

- Delete Tutorial using axios DELETE request:

![axios-delete-request-example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6i1em0pnrpf7jyf2q1f1.png)

<h2>Source Code</h2>
<em>index.html</em>
```html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Axios Requests example</title>
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css"
    />
  </head>
  <body>
    <div class="container my-3" style="max-width: 600px">
      <h3>Axios Requests example</h3>

      <div class="card mt-3">
        <div class="card-header">Axios GET Request - BezKoder.com</div>
        <div class="card-body">
          <div class="input-group input-group-sm">
            <button class="btn btn-sm btn-primary" onclick="getAllData()">Get All</button>

            <input type="text" id="get-id" class="form-control ml-2" placeholder="Id">
            <div class="input-group-append">
              <button class="btn btn-sm btn-primary" onclick="getDataById()">Get by Id</button>
            </div>

            <input type="text" id="get-title" class="form-control ml-2" placeholder="Title">
            <div class="input-group-append">
              <button class="btn btn-sm btn-primary" onclick="getDataByTitle()">Find By Title</button>
            </div>

            <button class="btn btn-sm btn-warning ml-2" onclick="clearGetOutput()">Clear</button>
          </div>   
          
          <div id="getResult"></div>
        </div>
      </div>

      <div class="card mt-3">
        <div class="card-header">Axios POST Request - BezKoder.com</div>
        <div class="card-body">
          <div class="form-group">
            <input type="text" class="form-control" id="post-title" placeholder="Title">
          </div>
          <div class="form-group">
            <input type="text" class="form-control" id="post-description" placeholder="Description">
          </div>
          <button class="btn btn-sm btn-primary" onclick="postData()">Post Data</button>
          <button class="btn btn-sm btn-warning" onclick="clearPostOutput()">Clear</button>

          <div id="postResult"></div>
        </div>
      </div>

      <div class="card mt-3">
        <div class="card-header">Axios PUT Request - BezKoder.com</div>
        <div class="card-body">
          <div class="form-group">
            <input type="text" class="form-control" id="put-id" placeholder="Id">
          </div>
          <div class="form-group">
            <input type="text" class="form-control" id="put-title" placeholder="Title">
          </div>
          <div class="form-group">
            <input type="text" class="form-control" id="put-description" placeholder="Description">
          </div>
          <div class="form-check">
            <input type="checkbox" class="form-check-input" id="put-published">
            <label class="form-check-label" for="put-published">Publish</label>
          </div>
          <div class="form-group mt-2">
            <button class="btn btn-sm btn-primary" onclick="putData()">Update Data</button>
            <button class="btn btn-sm btn-warning" onclick="clearPutOutput()">Clear</button>
          </div>

          <div id="putResult"></div>
        </div>
      </div>

      <div class="card mt-3">
        <div class="card-header">Axios DELETE Request - BezKoder.com</div>
        <div class="card-body">
          <div class="input-group input-group-sm">
            <button class="btn btn-sm btn-danger" onclick="deleteAllData()">Delete All</button>

            <input type="text" id="delete-id" class="form-control ml-2" placeholder="Id">
            <div class="input-group-append">
              <button class="btn btn-sm btn-danger" onclick="deleteDataById()">Delete by Id</button>
            </div>

            <button class="btn btn-sm btn-warning ml-2" onclick="clearDeleteOutput()">Clear</button>
          </div>    
          
          <div id="deleteResult"></div>      
        </div>
      </div>
    </div>

    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    <script src="main.js"></script>
  </body>
</html>
```

<em>index.html</em>
```js
const instance = axios.create({
  baseURL: "http://localhost:8080/api",
  headers: {
    "Content-Type": "application/json",
  },
});

function htmlizeResponse(res) {
  return `<div class="alert alert-secondary mt-2" role="alert"><pre>` + JSON.stringify(res, null, 2) + "</pre></div>";
}

async function getAllData() {
  let resultElement = document.getElementById("getResult");
  resultElement.innerHTML = "";

  try {
    const res = await instance.get("/tutorials");

    const result = {
      status: res.status + "-" + res.statusText,
      headers: res.headers,
      data: res.data,
    };

    resultElement.innerHTML = htmlizeResponse(result);
  } catch (err) {
    resultElement.innerHTML = htmlizeResponse(err);
  }
}

async function getDataById() {
  let resultElement = document.getElementById("getResult");
  resultElement.innerHTML = "";

  const id = document.getElementById("get-id").value;

  if (id) {
    try {
      const res = await instance.get(`/tutorials/${id}`);

      const result = {
        status: res.status + "-" + res.statusText,
        headers: res.headers,
        data: res.data,
      };

      resultElement.innerHTML = htmlizeResponse(result);
    } catch (err) {
      resultElement.innerHTML = htmlizeResponse(err);
    }
  }
}

async function getDataByTitle() {
  let resultElement = document.getElementById("getResult");
  resultElement.innerHTML = "";

  const title = document.getElementById("get-title").value;

  if (title) {
    try {
      // const res = await instance.get(`/tutorials?title=${title}`);
      const res = await instance.get("/tutorials", {
        params: {
          title: title
        }
      });

      const result = {
        status: res.status + "-" + res.statusText,
        headers: res.headers,
        data: res.data,
      };

      resultElement.innerHTML = htmlizeResponse(result);
    } catch (err) {
      resultElement.innerHTML = htmlizeResponse(err);
    }
  }
}

async function postData() {
  let resultElement = document.getElementById("postResult");
  resultElement.innerHTML = "";

  const title = document.getElementById("post-title").value;
  const description = document.getElementById("post-description").value;

  try {
    const res = await instance.post("/tutorials", {
      title: title,
      description: description,
    });

    const result = {
      status: res.status + "-" + res.statusText,
      headers: res.headers,
      data: res.data,
    };

    resultElement.innerHTML = htmlizeResponse(result);
  } catch (err) {
    resultElement.innerHTML = htmlizeResponse(err);
  }
}

async function putData() {
  let resultElement = document.getElementById("putResult");
  resultElement.innerHTML = "";

  const id = document.getElementById("put-id").value;
  const title = document.getElementById("put-title").value;
  const description = document.getElementById("put-description").value;
  const published = document.getElementById("put-published").checked;

  try {
    const res = await instance.put(`/tutorials/${id}`, {
      title: title,
      description: description,
      published: published
    });

    const result = {
      status: res.status + "-" + res.statusText,
      headers: res.headers,
      data: res.data,
    };

    resultElement.innerHTML = htmlizeResponse(result);
  } catch (err) {
    resultElement.innerHTML = htmlizeResponse(err);
  }
}

async function deleteAllData() {
  let resultElement = document.getElementById("deleteResult");
  resultElement.innerHTML = "";

  try {
    const res = await instance.delete("/tutorials");

    const result = {
      status: res.status + "-" + res.statusText,
      headers: res.headers,
      data: res.data,
    };

    resultElement.innerHTML = htmlizeResponse(result);
  } catch (err) {
    resultElement.innerHTML = htmlizeResponse(err);
  }
}

async function deleteDataById() {
  let resultElement = document.getElementById("deleteResult");
  resultElement.innerHTML = "";

  const id = document.getElementById("delete-id").value;

  try {
    const res = await instance.delete(`/tutorials/${id}`);

    const result = {
      status: res.status + "-" + res.statusText,
      headers: res.headers,
      data: res.data,
    };

    resultElement.innerHTML = htmlizeResponse(result);
  } catch (err) {
    resultElement.innerHTML = htmlizeResponse(err);
  }
}

function clearGetOutput() {
  document.getElementById("getResult").innerHTML = "";
}

function clearPostOutput() {
  document.getElementById("postResult").innerHTML = "";
}

function clearPutOutput() {
  document.getElementById("putResult").innerHTML = "";
}

function clearDeleteOutput() {
  document.getElementById("deleteResult").innerHTML = "";
}
```

Source: [BezKoder](https://www.bezkoder.com/axios-request/)

With this Axios tutorial, you've known many ways to make GET/POST/PUT/DELETE request using Axios (with headers, params, body...). You can also use it in:

- React App: <a href="https://www.bezkoder.com/react-axios-example/">React Axios example – Get/Post/Put/Delete with Rest API</a>
Or: <a href="https://www.bezkoder.com/react-query-axios/">React Query and Axios example with Rest API</a>

- Vue App: <a href="https://www.bezkoder.com/vue-axios-example/">Vue Axios example – Get/Post/Put/Delete with Rest API</a>

<h2>Further Reading</h2>
<ul>
	<li><a href="https://github.com/axios/axios">https://github.com/axios/axios</a></li>
	<li><a href="https://www.bezkoder.com/axios-file-upload/">Axios File upload</a></li>
	<li><a href="https://www.bezkoder.com/axios-interceptors-refresh-token/">Axios Interceptors tutorial with Refresh Token example</a></li>
	<li><a href="https://www.bezkoder.com/react-crud-web-api/">React CRUD example with Axios</a></li>
	<li><a href="https://www.bezkoder.com/react-redux-crud-example/">React Redux CRUD example with Axios</a></li>
	<li><a href="https://www.bezkoder.com/vue-js-crud-app/">Vue 2 CRUD Application with Axios & Vue Router</a></li>
	<li><a href="https://www.bezkoder.com/vue-3-crud/">Vue 3 CRUD example with Axios & Vue Router</a></li>
</ul>