Steps to Create an API Client with TypeScript

Steps to Create an API Client with TypeScript


In modern web applications, interacting with APIs is often inevitable. TypeScript, as a powerful superset of JavaScript, makes the development process more reliable and sustainable, especially in large applications. In this article, we will cover the steps to create a simple API client using TypeScript. We will observe how our API client sends requests to a specific RESTful service and processes the returned data.

What is TypeScript?

TypeScript is an open-source programming language developed by Microsoft. As a superset of JavaScript, it supports static type checking, class-based object-oriented programming, and modern JavaScript features. By using TypeScript, you can achieve a more robust structure in your large and complex projects, organize your code better, and speed up the debugging process.

Creating an API Client

To create a simple API client with TypeScript, you first need to install the necessary dependencies. Let's install the Axios library by running the following npm command in the project directory:

npm install axios

Now, let's create a simple `apiClient.ts` file. In this file, we will define a class that will send requests to the API:

import axios, { AxiosInstance } from 'axios';

class ApiClient {
    private axiosInstance: AxiosInstance;

    constructor(baseURL: string) {
        this.axiosInstance = axios.create({
            baseURL: baseURL,
            timeout: 1000,
        });
    }

    public async get(endpoint: string) {
        try {
            const response = await this.axiosInstance.get(endpoint);
            return response.data;
        } catch (error) {
            console.error('API request error:', error);
            throw error;
        }
    }
}

export default ApiClient;

In the code above, we use the Axios library to define the API client. In the `constructor` method, we get the base URL and create the Axios instance. Also, with the `get` method, we send a GET request to the specified endpoint. In case of an error, a simple error message is logged.

Usage Example

We can now use our client. Below, let's create a `main.ts` file to show how this client can be used:

import ApiClient from './apiClient';

const client = new ApiClient('https://jsonplaceholder.typicode.com');

async function fetchData() {
    try {
        const data = await client.get('/posts');
        console.log(data);
    } catch (error) {
        console.error('Error occurred while retrieving data:', error);
    }
}

fetchData();

Here, we are fetching data from the JSONPlaceholder API. The `fetchData` function uses our API client to send a GET request to the '/posts' endpoint and logs the result to the console.

Conclusion

In this article, we learned the steps to create a simple API client using TypeScript. The type safety and debugging ease provided by TypeScript greatly simplify the development process. By adding additional functionalities for more complex API interactions, you can extend this basic API client and discover more of TypeScript's advantages.