How to call api using typescript?


In this tutorial, we will learn about calling APIs using TypeScript. TypeScript is a statically-typed superset of JavaScript that adds type checking to the language. It provides enhanced tooling and helps catch errors during development.

When working with APIs, we often need to make HTTP requests to send data and retrieve information. TypeScript allows us to write clean and organized code while interacting with APIs, making it easier to handle responses and work with the returned data.

Throughout this tutorial, we will explore different methods and libraries available in TypeScript for making API calls. We will focus on using the axios library, which is widely used and offers a simple and intuitive interface for making HTTP requests.

Syntax

Users can follow the syntax below to create API calls using TypeScript −

import axios from 'axios';
async function fetchData() {
   try {
      const response = await axios.get(apiUrl);
      // Handle the response
   } catch (error) {
      // Handle the error
   }
}

The above syntax demonstrates a basic structure for making an API call using the axios library. We import the axios module, define an async function called fetchData(), and use the axios.get() method to send a GET request to the specified API endpoint (apiUrl). The response can be handled within the try block, and any errors can be caught in the catch block.

Different Libraries for Making API Calls in TypeScript

When it comes to making API calls in TypeScript, there are several HTTP libraries available, each offering unique features and options. Here are some commonly used libraries −

axios − Axios is a popular HTTP client library that supports both browser and Node.js environments. It provides a simple and intuitive API for making HTTP requests, handling headers, setting request parameters, and managing responses. Axios also supports features like request cancellation, interceptors, and automatic JSON parsing.

node-fetch − Node-fetch is a lightweight library that brings the fetch API to Node.js. It allows you to make HTTP requests using the same syntax and concepts as the fetch API in browsers. Node-fetch supports features like setting headers, handling cookies, and working with streams.

isomorphic-fetch − Isomorphic-fetch is a cross-platform library that provides a fetch-like API for making HTTP requests in both browser and Node.js environments. It aims to offer consistent behavior across different platforms and supports features like request and response transformation, handling cookies, and setting headers.

These libraries abstract away the complexities of making HTTP requests and provide convenient methods for handling API interactions. Users can choose the library that best aligns with their project requirements and preferences.

Example 1

In this example, we have created a function called fetchUsers() that uses Axios to make a GET request to the 'https://jsonplaceholder.typicode.com/users' endpoint.

After receiving the response, we extract the user data from the response.data property.

Finally, we log the list of users to the console using console.log(). Users can observe the list of users in the output when running this script.

import axios from 'axios';
async function fetchUsers() {
   try {
      const response = await axios.get('https://jsonplaceholder.typicode.com/users');
      const users = response.data;
      console.log('List of users:');
      console.log(users);
   } catch (error) {
      console.error('Error fetching users:', error.message);
   }
}
fetchUsers();

Output

List of users:
[
   {
      id: 1,
      name: 'Leanne Graham',
      username: 'Bret',
      email: 'Sincere@april.biz',
      address: {
         street: 'Kulas Light',
         suite: 'Apt. 556',
         city: 'Gwenborough',
         zipcode: '92998-3874',
         geo: [Object]
      },
      phone: '1-770-736-8031 x56442',
      website: 'hildegard.org',
      company: {
         name: 'Romaguera-Crona',
         catchPhrase: 'Multi-layered client-server neural-net',
         bs: 'harness real-time e-markets'
      }
   },{
      id: 2,
      name: 'Ervin Howell',
      username: 'Antonette',
      email: 'Shanna@melissa.tv',
      address: {
         street: 'Victor Plains',
         suite: 'Suite 879',
         city: 'Wisokyburgh',
         zipcode: '90566-7771',
         geo: [Object]
      },
      phone: '010-692-6593 x09125',
      website: 'anastasia.net',
      company: {
         name: 'Deckow-Crist',
         catchPhrase: 'Proactive didactic contingency',
         bs: 'synergize scalable supply-chains'
      }
   },
]

Example 2

In this example, we import the node-fetch library and define an async function called fetchUserDetails(). This function uses fetch() to make a GET request to the 'https://reqres.in/api/users/1' endpoint, which retrieves the details of the user with ID 1.

After receiving the response, we use response.json() to parse the response body as JSON and obtain the user data.

Finally, we log the user details to the console using console.log(). Users can observe the user details in the output when running this script.

import fetch from 'node-fetch';
async function fetchUserDetails() {
   try {
      const response = await fetch('https://reqres.in/api/users/1');
      const data = await response.json();
      console.log('User details:');
      console.log(data);
   } catch (error) {
      console.error('Error fetching user details:', error.message);
   }
}
fetchUserDetails();

Output

User details:{
   data: {
      id: 1,
      email: 'george.bluth@reqres.in',
      first_name: 'George',
      last_name: 'Bluth',
      avatar: 'https://reqres.in/img/faces/1-image.jpg'
   },
   support: {
      url: 'https://reqres.in/#support-heading',
      text: 'To keep ReqRes free, contributions towards server costs are appreciated!'
   }
}

Example 3

In this example, we define the Chuck Norris API endpoint URL as chuckNorrisUrl.

We create an async function called fetchRandomJoke() that uses the Fetch API to send a GET request to the Chuck Norris API.

After receiving the response, we parse the JSON data using response.json(). The joke is extracted from the value property of the response data.

Finally, we call fetchRandomJoke() to initiate the API call and display the random Chuck Norris joke on the webpage.

Users can observe the joke of the day in the output.

import fetch from 'isomorphic-fetch';
const chuckNorrisUrl = 'https://api.chucknorris.io/jokes/random';
async function fetchRandomJoke() {
   try {
      const response = await fetch(chuckNorrisUrl);
      const data = await response.json();
      const joke = data.value;
      console.log("Joke of the day: ", joke);
   } catch (error) {
      console.error('Error fetching joke:', error.message); 
   }
}
fetchRandomJoke();

Output

Joke of the day:  Chuck Norris can skeletonize a cow in under two minutes.

In this tutorial, we've learned how to call APIs using TypeScript. We explored the syntax for making API calls and handling responses using the axios library. Additionally, we saw some examples of how to retrieve user data from an API using , node-fetch & isomorphic-fetch libraries. By understanding these concepts, users can now integrate API calls into their TypeScript projects and fetch data from external sources efficiently.

Updated on: 10-Aug-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements