Published on

TypeScript: HTTP Requests with Axios

Table of Contents

If you're building a web application, you'll most likely need to make HTTP requests to fetch data from an API. One popular library for making HTTP requests in JavaScript is Axios. In this guide, we'll explore how to use Axios with TypeScript to make HTTP requests.

Setup

First, let's install Axios and its TypeScript types using npm:

npm install axios @types/axios

This will also give you access to TypeScript type definitions for Axios, which can help with type checking and editor autocompletion.

GET

Now that we have Axios installed, let's start by creating an interface for our API response. Here, we'll be making a GET request to fetch a list of members from an API. Here's what our Member interface looks like:

ts-interface.tsx
interface Member {
  id: number
  fullName: string
  subscriptionID?: string
  createdAt: string
  isActive: boolean
}

Now, let's create a function to make our HTTP request. Here, we'll be using the GET method to fetch our list of members:

ts-get-fnc.tsx
import axios, { AxiosResponse } from 'axios';

interface Member {
  id: number;
  fullName: string;
  subscriptionID?: number;
  createdAt: Date;
  isActive: boolean;
}
  const fetchMembers = async (): Promise<Member[]> => {
    try {
      const config = {
        headers: {
          'Content-Type': 'application/json',
          //Authorization: `Bearer ${API_TOKEN}`, //if auth is needed
        },
      }

      const { data } = await axios.get<Member[]>(
        'https://6414dbc28dade07073ca4f04.mockapi.io/api/v1/members',
        config
      )
      console.table(members)
      return data
    } catch (error) {
      console.error(error)
      return []
    }
  }

  fetchMembers().then(members => console.log("GET /members finished !") )

In the code above, we're using the axios.get method to fetch our list of members. We're also specifying the generic type of our axios call AxiosResponse.

axios-signature
Axios.get<Member[], AxiosResponse<Member[], any>, any>(     
  url: string,
  config?: AxiosRequestConfig<any> | undefined
  ): Promise<AxiosResponse<Member[], any>>

This tells TypeScript that our response should be an array of Member objects.

We're also using the async and await keywords to make our HTTP request asynchronous. This allows us to wait for the response to be returned before continuing with our code.

POST

ts-post.tsx
  const createMember = async (newMember: Member): Promise<Member> => {
    try {
      const config = {
        headers: {
          'Content-Type': 'application/json',
          // Authorization: `Bearer ${API_TOKEN}`, //if auth is needed
        },
      }

      const { data } = await axios.post<Member>(
        'https://6414dbc28dade07073ca4f04.mockapi.io/api/v1/members',
        newMember, // 👈🏽 Here we pass the object as HTTP.body
        config
      )

      return data
    } catch (error) {
      console.error(error)
      throw error
    }
  }

  createMember(newMember).then((member) => console.log('POST /members finished !'))

The createMember function accepts an object representing a new member and sends a POST request to create that member on the server. The server should respond with the new member object, which is returned from the function.

That's it! We've successfully made HTTP requests using Axios and TypeScript.

In conclusion, Axios is a powerful library for making HTTP requests in JavaScript, and using it with TypeScript can make your code more type-safe and easier to maintain. By following the steps outlined in this guide, you can easily make HTTP requests using Axios and TypeScript in your own projects.