DEV Community

NETIC
NETIC

Posted on • Edited on

How to consume Web API in TypeScript using Axios

Web APIs are a great way to retrieve data from a server and use it in your application. TypeScript is a statically-typed language that provides better type checking, code completion, and documentation. In this article, we will discuss how to consume Web APIs in TypeScript.

Install Required Packages

We will use Axios, a promise-based HTTP client, to make HTTP requests, and we will use TypeScript's type definitions for Axios. Run the following command in your terminal:

npm install axios @types/axios
Enter fullscreen mode Exit fullscreen mode

Create an Interface for Response

To make our code more readable and maintainable, we will create an interface for the response we expect from the Web API. This will allow TypeScript to check that our code is correct and provide better code completion and documentation.

For example, if we are retrieving a list of users from the server, we can create an interface like this:

interface User {
  id: number;
  name: string;
  email: string;
}
Enter fullscreen mode Exit fullscreen mode

Make HTTP Requests

Now we are ready to make HTTP requests to the Web API. We will use Axios to make GET, POST, PUT, and DELETE requests. For example, to retrieve a list of users from the server, we can use the following code:

import axios from 'axios';

axios.get<User[]>('https://example.com/api/users')
  .then((response) => {
    const users = response.data;
    console.log(users);
  })
  .catch((error) => {
    console.error(error);
  });
Enter fullscreen mode Exit fullscreen mode

In the above code, we make a GET request to the URL https://example.com/api/users and expect a response of type User[]. We then log the list of users to the console.

Handle Errors

When making HTTP requests, errors can occur. To handle errors, we can use the .catch() method. For example, if the server returns a 404 error, we can display an error message to the user like this:

import axios from 'axios';

axios.get<User[]>('https://example.com/api/users')
  .then((response) => {
    const users = response.data;
    console.log(users);
  })
  .catch((error) => {
    console.error(error);
    alert('An error occurred. Please try again later.');
  });
Enter fullscreen mode Exit fullscreen mode

Use Async/Await

To make our code more readable, we can use the async/await syntax instead of the .then() and .catch() methods. For example, we can retrieve a list of users like this:

import axios from 'axios';

async function getUsers(): Promise<User[]> {
  try {
    const response = await axios.get<User[]>('https://example.com/api/users');
    return response.data;
  } catch (error) {
    console.error(error);
    throw new Error('An error occurred. Please try again later.');
  }
}

async function displayUsers() {
  try {
    const users = await getUsers();
    console.log(users);
  } catch (error) {
    alert(error.message);
  }
}

displayUsers();
Enter fullscreen mode Exit fullscreen mode

In the above code, we define an async function getUsers() that retrieves a list of users from the server. We also define an async function displayUsers() that calls getUsers() and logs the list of users to the console. If an error occurs, we display an error message to the user.

Conclusion

Consuming Web APIs in TypeScript is easy and provides many benefits. By creating interfaces for the response we expect, using Axios to make HTTP requests, handling errors, and using

Top comments (0)