TypeScript is a superset of JavaScript, which means it extends and improves its capabilities, making it an excellent choice for working with REST APIs. Here’s a step-by-step guide on how to use TypeScript to work with REST APIs:
1. **Creating a TypeScript project**: First, set up a new TypeScript project by installing TypeScript globally.
npm install -g typescript
Create a new project folder and initialize it with ‘npm init‘.
mkdir ts-rest-api
cd ts-rest-api
npm init -y
Now, initialize the TypeScript project by running:
tsc --init
2. **Installing required libraries**: In this example, we will be using ‘axios‘ to make HTTP requests and ‘@types/axios‘ for TypeScript definitions. To install these, run:
npm install axios
npm install --save-dev @types/axios
3. **Defining data types**: REST APIs deal with data, and it is crucial to define the data types and structure expected from the API response. For this example, let’s assume the REST API returns a list of users with their ‘id‘, ‘name‘, ‘email‘, and ‘address‘.
Create a new file named ‘types.ts‘ and define the data types as follows:
export interface User {
id: number;
name: string;
email: string;
address: Address;
}
export interface Address {
street: string;
city: string;
zipcode: string;
}
4. **Building a helper function to work with the REST API**: To make it easier to work with the REST API, you can create a helper function that abstracts the API calls. In this case, we will build a simple function that retrieves all users and another one to retrieve a specific user by ID.
Create a new file named ‘api.ts‘, and implement the helper functions for fetching users:
import axios from 'axios';
import { User } from './types';
// Base URL for the REST API
const API_BASE_URL = 'https://jsonplaceholder.typicode.com';
export async function fetchUsers(): Promise<User[]> {
const response = await axios.get<User[]>(`${API_BASE_URL}/users`);
return response.data;
}
export async function fetchUserById(userId: number): Promise<User> {
const response = await axios.get<User>(`${API_BASE_URL}/users/${userId}`);
return response.data;
}
5. **Using the helper functions**: Now that we defined the types and helper functions, we can use them to interact with the REST API.
Create a new file named ‘main.ts‘ and use the ‘fetchUsers‘ and ‘fetchUserById‘ functions:
import { User } from "./types";
import { fetchUsers, fetchUserById } from "./api";
async function main() {
const users: User[] = await fetchUsers();
console.log("All users:");
console.table(users);
const singleUser: User = await fetchUserById(1);
console.log("User with ID 1:");
console.table(singleUser);
}
main();
6. **Compile and run the TypeScript code**: To compile the TypeScript code to JavaScript, run:
tsc
This will generate a set of JavaScript files that can be executed using Node.js. To run the ‘main.js‘ file, execute:
node main.js
You will see the output with the list of all users and the details of the User with ID 1 fetched from the REST API.
This example demonstrates a basic way of using TypeScript to work with REST APIs. You can extend this approach to perform other actions such as creating, updating, and deleting resources via the API using the ‘axios‘ library and the defined data types.