axios typescript get with code examples

In the world of modern web development, the use of APIs has become ubiquitous. There are a plethora of choices when it comes to handling API requests, but one of the most popular and widely used libraries is Axios. Axios is a promise-based HTTP client that supports all types of HTTP requests. Its popularity comes from its ease of use, robustness, and backward compatibility.

Axios, which is written in JavaScript, is used in many web frameworks such as Node.js and React Native. However, to ensure type safety and avoid common JavaScript mistakes, we can use TypeScript with Axios. TypeScript is a strongly typed superset of JavaScript that adds optional static typing to the language.

In this article, we'll discuss how to use Axios with TypeScript. We'll explore the syntax and the benefits of using it, and provide code examples of Axios requests.

Axios with TypeScript

To use Axios in TypeScript, we need to install Axios and the types package for TypeScript. We can do that by running the following command in the terminal:

npm install axios @types/axios

Once installed, we can import Axios into our TypeScript file using the following code:

import axios, { AxiosResponse } from 'axios';

Here, we import Axios and the AxiosResponse interface from the Axios module. The AxiosResponse interface is used to declare the generic response type returned by Axios.

Using Axios with TypeScript is similar to using it with plain JavaScript. We can use the same methods and properties provided by Axios, such as get, post, put, delete, interceptors, and many more.

GET Request with Axios in TypeScript

Let's start with a simple example of making a GET request using Axios with TypeScript. In this example, we'll fetch a list of users from a public API and log the response to the console.

import axios, { AxiosResponse } from 'axios';

interface User {
  id: number;
  name: string;
  username: string;
  email: string;
}

axios.get('https://jsonplaceholder.typicode.com/users')
  .then((response: AxiosResponse<User[]>) => {
    const users = response.data;
    console.log(users);
  })
  .catch((error) => {
    console.error(error);
  });

Here, we declare an interface called User that represents the structure of the data we receive from the API. We then use the get method of Axios to fetch data from the API and assign it to the response variable.

We also declare the generic response type AxiosResponse<User[]> that represents the type of data we're expecting from the API. The response object has a property called data, which contains the response body returned by the server.

If there are no errors, we log the response data to the console. If an error occurs, we catch the error and log it to the console.

POST Request with Axios in TypeScript

Now, let's look at an example of making a POST request using Axios with TypeScript. In this example, we'll create a new user on a public API and log the response to the console.

import axios, { AxiosResponse } from 'axios';

interface User {
  name: string;
  username: string;
  email: string;
}

axios.post('https://jsonplaceholder.typicode.com/users', {
    name: 'Jane Doe',
    username: 'janedoe',
    email: 'jane.doe@example.com',
})
  .then((response: AxiosResponse<User>) => {
    const newUser = response.data;
    console.log(newUser);
  })
  .catch((error) => {
    console.error(error);
  });

Here, we use the post method of Axios to create a new user on the API. We pass an object with the user's details as the second argument.

We also declare the generic response type AxiosResponse<User> that represents the type of data we're expecting from the API. If there are no errors, we log the response data to the console.

If an error occurs, we catch the error and log it to the console.

Conclusion

Using Axios with TypeScript provides several benefits. It ensures type safety and helps to avoid common JavaScript mistakes.

In this article, we explored the syntax and the benefits of using Axios with TypeScript, and provided code examples of Axios requests.

Axios is a powerful library that simplifies API requests, and TypeScript is a strong typing tool that adds an extra layer of safety to our code. Together, they make a great combination for modern web development.

Sure! I'll expand on the topics we covered in the previous article.

Axios' Promise-based Approach

Axios is a promise-based library, which means it returns a promise when we make a request. Promises are objects representing the eventual completion or failure of an asynchronous operation. They make it easier to handle asynchronous operations and keep the code organized.

In Axios, we use the .then() and .catch() methods to handle the promise returned by a request. The .then() method is called when the request succeeds, and the response is received. The .catch() method is called when an error occurs.

In TypeScript, we can declare the expected response type to avoid type errors in our code. We can declare the response type by using the AxiosResponse interface or by declaring a custom interface that matches the response data.

Axios' Interceptors

Interceptors are functions that we can use to modify a request or response before they're sent or received. We can use interceptors for a variety of tasks, such as adding headers, logging, authentication, or error handling.

Axios provides two types of interceptors: Request interceptors and Response interceptors.

Request interceptors are used to modify the request before it's sent to the server. We can use request interceptors to add headers, modify data, or set authentication tokens.

Response interceptors are used to modify the response returned by the server before it reaches the application. We can use response interceptors to modify the response data, catch errors, or handle authentication challenges.

In TypeScript, we can declare the type of the interceptor function using the AxiosInterceptorManager interface.

For example, the following code shows how to add a request interceptor that adds a token to the request headers.

import axios, { AxiosResponse } from 'axios';

interface User {
  id: number;
  name: string;
  username: string;
  email: string;
}

axios.interceptors.request.use((config) => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers['Authorization'] = `Bearer ${token}`;
  }
  return config;
});

axios.get('https://jsonplaceholder.typicode.com/users')
  .then((response: AxiosResponse<User[]>) => {
    const users = response.data;
    console.log(users);
  })
  .catch((error) => {
    console.error(error);
  });

In this example, we're adding a request interceptor that adds an Authorization header to the request if a token exists in the local storage. We're checking for the token in the localStorage using the getItem method.

Axios' Cancel Token

Axios provides a mechanism for cancelling requests using cancel tokens. A cancel token is an object that's passed to a request, and it has a cancel property that can be called to cancel the request.

To create a cancel token, we use the CancelToken factory function provided by Axios. We can pass a function to the CancelToken function, and it will be called if the request is cancelled.

import axios, { AxiosResponse, CancelToken } from 'axios';

interface User {
  id: number;
  name: string;
  username: string;
  email: string;
}

const source = axios.CancelToken.source();
const config = { cancelToken: source.token };

axios.get('https://jsonplaceholder.typicode.com/users', config)
  .then((response: AxiosResponse<User[]>) => {
    const users = response.data;
    console.log(users);
  })
  .catch((error) => {
    if (axios.isCancel(error)) {
      console.log('Request Cancelled:', error.message);
    } else {
      console.error(error);
    }
  });

source.cancel('Request Cancelled by user');

In this example, we're creating a cancel token using the source object and passing the token property to the request config. We're also passing a message to the cancel method of the source to indicate the reason for cancelling the request.

If the request is cancelled, the isCancel method provided by Axios can be used to check if the error is a cancellation error. If the error is a cancellation error, the message provided to the cancel method will be logged to the console.

Conclusion

Axios is a powerful and flexible library that makes it easy to work with APIs. When combined with TypeScript, it becomes more robust and easier to maintain. In this article, we covered some of the features of Axios in TypeScript, such as its promise-based approach, interceptors, and cancel tokens.

By understanding these features of Axios, we can write more performant and robust code that's easier to maintain and scale.

Popular questions

  1. What is Axios?

Axios is a promise-based HTTP client library that supports all types of HTTP requests. Its popularity comes from its ease of use, robustness, and backward compatibility.

  1. What is Promise-based approach and how is it used in Axios?

A Promise-based approach means that Axios returns a promise when we make a request. A promise is an object representing the eventual completion or failure of an asynchronous operation. In Axios, we use the .then() and .catch() methods to handle the promise returned by a request.

  1. How can we declare the expected response type in TypeScript when using Axios?

In TypeScript, we can declare the expected response type in Axios by using the AxiosResponse interface or by declaring a custom interface that matches the response data.

  1. What are Axios interceptors, and how are they used in TypeScript?

Interceptors are functions that we can use to modify a request or response before they're sent or received. We can use interceptors for a variety of tasks, such as adding headers, logging, authentication, or error handling. In TypeScript, we can declare the type of the interceptor function using the AxiosInterceptorManager interface.

  1. What are cancel tokens in Axios, and how are they used in TypeScript?

Cancel tokens in Axios provide a mechanism for cancelling requests. A cancel token is an object that's passed to a request, and it has a cancel property that can be called to cancel the request. To create a cancel token, we use the CancelToken factory function provided by Axios. In TypeScript, we can use the CancelToken and AxiosCancelToken interfaces to implement cancel tokens in our code.

Tag

"TypeScript Fetching"

As a senior DevOps Engineer, I possess extensive experience in cloud-native technologies. With my knowledge of the latest DevOps tools and technologies, I can assist your organization in growing and thriving. I am passionate about learning about modern technologies on a daily basis. My area of expertise includes, but is not limited to, Linux, Solaris, and Windows Servers, as well as Docker, K8s (AKS), Jenkins, Azure DevOps, AWS, Azure, Git, GitHub, Terraform, Ansible, Prometheus, Grafana, and Bash.

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top