You are currently viewing Using Axios with TypeScript

Using Axios with TypeScript

TypeScript, a statically typed superset of JavaScript, brings the benefits of strong typing and improved developer experience to JavaScript applications. When combined with Axios, a promise-based HTTP client, TypeScript enhances the process of making HTTP requests by providing type safety and improved code readability.

This comprehensive guide will explore how to use Axios with TypeScript, covering setup, making GET and POST requests, handling errors, and creating custom Axios instances. Each section will include full executable code examples with detailed explanations. By the end of this article, you will have a solid understanding of how to leverage TypeScript with Axios to build robust and maintainable web applications.

Setting Up Axios with TypeScript

To get started with Axios and TypeScript, you need to install the necessary packages and configure TypeScript in your project.

Installing Axios and TypeScript

Using npm:

npm install axios typescript @types/node @types/axios

Using yarn:

yarn add axios typescript @types/node @types/axios

Configuring TypeScript

Create a tsconfig.json file to configure TypeScript in your project.

{
  "compilerOptions": {
    "target": "ES6",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src"]
}

This configuration sets the target to ES6, uses commonjs modules, and includes strict type-checking options. The include option specifies the directory to be compiled by TypeScript.

Making GET Requests with Axios and TypeScript

Introduction to GET Requests

GET requests are used to retrieve data from a server. TypeScript enhances GET requests by providing type definitions for the request and response data, ensuring type safety and reducing runtime errors.

Code Example: Typing the GET Request

First, define an interface for the response data:

// src/interfaces/User.ts
export interface User {
  id: number;
  name: string;
  email: string;
}

Next, create a function to fetch data using Axios with TypeScript:

// src/api/userApi.ts
import axios, { AxiosResponse } from 'axios';
import { User } from '../interfaces/User';

const fetchUsers = async (): Promise<User[]> => {

  try {
    const response: AxiosResponse<User[]> = await axios.get('https://api.example.com/users');
    return response.data;
  } catch (error) {
    throw new Error('Error fetching users');
  }

};

export default fetchUsers;

In this example, the fetchUsers function uses Axios to send a GET request to the specified URL. The response data is typed as an array of User objects, ensuring type safety. If the request fails, an error is thrown with a descriptive message.

Making POST Requests with Axios and TypeScript

Introduction to POST Requests

POST requests are used to send data to a server, typically to create a new resource. TypeScript enhances POST requests by providing type definitions for the request payload and response data.

Code Example: Typing the POST Request

First, define an interface for the request payload and response data:

// src/interfaces/User.ts
export interface User {
  id: number;
  name: string;
  email: string;
}

export interface CreateUserPayload {
  name: string;
  email: string;
}

export interface CreateUserResponse {
  user: User;
}

Next, create a function to send data using Axios with TypeScript:

// src/api/userApi.ts
import axios, { AxiosResponse } from 'axios';
import { CreateUserPayload, CreateUserResponse } from '../interfaces/User';

const createUser = async (payload: CreateUserPayload): Promise<CreateUserResponse> => {

  try {
    const response: AxiosResponse<CreateUserResponse> = await axios.post('https://api.example.com/users', payload);
    return response.data;
  } catch (error) {
    throw new Error('Error creating user');
  }

};

export default createUser;

In this example, the createUser function uses Axios to send a POST request with a payload of type CreateUserPayload. The response data is typed as CreateUserResponse, ensuring type safety. If the request fails, an error is thrown with a descriptive message.

Handling Errors with Axios and TypeScript

Introduction to Error Handling

Error handling is crucial when making HTTP requests, as it allows you to manage failures and provide feedback to users. TypeScript enhances error handling by providing type definitions for errors and responses.

Code Example: Typing and Handling Errors

First, create a custom error interface:

// src/interfaces/ApiError.ts
export interface ApiError {
  message: string;
  status: number;
}

Next, update the fetchUsers function to handle errors more precisely:

// src/api/userApi.ts
import axios, { AxiosResponse, AxiosError } from 'axios';
import { User } from '../interfaces/User';
import { ApiError } from '../interfaces/ApiError';

const fetchUsers = async (): Promise<User[]> => {

  try {

    const response: AxiosResponse<User[]> = await axios.get('https://api.example.com/users');
    return response.data;

  } catch (error) {

    if (axios.isAxiosError(error)) {
      const axiosError = error as AxiosError<ApiError>;
      throw new Error(axiosError.response?.data.message || 'Unknown error');
    }

    throw new Error('Error fetching users');

  }

};

export default fetchUsers;

In this example, the fetchUsers function handles Axios errors specifically by checking if the error is an instance of AxiosError. The error message is extracted from the response data if available, providing more precise error handling.

Creating Custom Axios Instances with TypeScript

Introduction to Axios Instances

Creating custom Axios instances allows you to define different configurations for different parts of your application. TypeScript enhances this process by providing type definitions for the instance configurations and interceptors.

Code Example: Typing and Configuring Axios Instances

First, create a custom Axios instance:

// src/api/axiosConfig.ts
import axios, { AxiosInstance } from 'axios';

const customAxiosInstance: AxiosInstance = axios.create({
  baseURL: 'https://api.example.com',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer token',
  },
  timeout: 10000, // 10 seconds timeout
});

// Add a request interceptor
customAxiosInstance.interceptors.request.use(
  config => {

    console.log('Request made with config:', config);
    return config;

  },
  error => {
    return Promise.reject(error);
  }
);

export default customAxiosInstance;

Next, update the fetchUsers function to use the custom Axios instance:

// src/api/userApi.ts
import axios, { AxiosResponse, AxiosError } from 'axios';
import customAxiosInstance from './axiosConfig';
import { User } from '../interfaces/User';
import { ApiError } from '../interfaces/ApiError';

const fetchUsers = async (): Promise<User[]> => {

  try {
    const response: AxiosResponse<User[]> = await customAxiosInstance.get('/users');
    return response.data;
  } catch (error) {

    if (axios.isAxiosError(error)) {
      const axiosError = error as AxiosError<ApiError>;
      throw new Error(axiosError.response?.data.message || 'Unknown error');
    }

    throw new Error('Error fetching users');

  }

};

export default fetchUsers;

In this example, a custom Axios instance is created with a base URL, default headers, and a timeout. A request interceptor is added to log the request configuration. The fetchUsers function is updated to use this custom Axios instance for making requests.

Conclusion

In this article, we explored how to use Axios with TypeScript to enhance the process of making HTTP requests in web applications. We covered the installation and setup of Axios and TypeScript, making GET and POST requests, handling errors, and creating custom Axios instances. By leveraging TypeScript, you can ensure type safety, improve code readability, and reduce runtime errors in your Axios requests.

Using TypeScript with Axios provides a powerful combination for building robust and maintainable web applications. I encourage you to experiment with these techniques, create custom configurations for different use cases, and implement precise error handling to build more reliable applications.

Additional Resources

To continue your learning journey with Axios and TypeScript, here are some additional resources:

  1. Axios Documentation: The official documentation provides comprehensive information and examples. Axios Documentation
  2. TypeScript Documentation: The official documentation provides detailed guides and tutorials. TypeScript Documentation
  3. React Documentation: The official documentation for React provides detailed guides and tutorials. React Documentation
  4. Handling HTTP Requests: Explore more about handling HTTP requests and responses effectively. HTTP Requests Guide

By utilizing these resources, you can deepen your understanding of Axios and TypeScript, enhancing your ability to build efficient and scalable web applications.

Leave a Reply