You are here: Home / Topics / Consuming Rest Api - Typescript

Consuming Rest Api - Typescript

Filed under: TypeScript on 2024-03-18 12:28:53

APIs are mechanisms that enable two software components to communicate with each other using a set of definitions and protocols. For example, the weather bureau's software system contains daily weather data.

Example 1: Fetch Data & use JSON.stringify
main.ts

import axios from 'axios';
async function fetchData() {
   try {
       const response = await
           axios.get('https://jsonplaceholder.typicode.com/users');
       const data = JSON.stringify(response.data, null, ' ');
       // console.log(data);
       data.forEach((element: any) => {
           console.log("Id: " + element.id + ", City: " +
               element.address.city);
       });
   } catch (error) {
       console.error('Error:', error);
   }
}
fetchData();

Example 2: Use Interface
main.ts

import axios from 'axios';
interface geo {
   lat: string;
   lng: string;
}
interface address {
   street: string;
   suite: string;
   city: string;
   zipcode: string;
   geo: geo;
}
async function fetchData() {
   try {
       const response = await
           axios.get('https://jsonplaceholder.typicode.com/users');
       const data = (response.data);
       // console.log(data);
       let address1: address;
       data.forEach((element: any) => {
           address1 = element.address as address;
           console.log(address1);
       });
   } catch (error) {
       console.error('Error:', error);
   }
}
fetchData();

Example 3: Use filter
main.ts

import axios from 'axios';
async function fetchData() {
   try {
       const response = await
           axios.get('https://jsonplaceholder.typicode.com/users');
       let data = (response.data);

       const filteredData = data.filter((person: any) =>
           person.address.zipcode === '31428-2261');
       filteredData.forEach((element: any) => {
           console.log(element);
       });
   } catch (error) {
       console.error('Error:', error);
   }
}
fetchData();

Example 4: Filter columns from Rest API Response
user.ts

export interface User {
   id: number;
   name: string;
   username: string;
   email: string;
   address: Address;
   phone: string;
   website: string;
   company: Company;
}
export interface Address {
   street: string;
   suit: string;
   city: string;
   zipcode: string;
   geo: Geo;
}
export interface Geo {
   lat: string;
   lng: string;
}
export interface Company {
   name: string;
   catchPhrase: string;
   bs: string;
}

customizedRecords.ts
export interface Records1 {
   id: number;
   email: string;
   zipcode: string;
}

main.ts
import axios from 'axios';
import { User, Address, Company } from './user';
import { Records1 } from './customizedRecords';
async function fetchData() {
   try {
       await
           axios.get < User[] > ('https://jsonplaceholder.typicode.com/users').the
       n((response) => {
           let users: User[] = response.data;
           // Extract only specific columns
           const record1: Records1[] = users.map(user => {
               const { id, email } = user;
               const zipcode = user.address.zipcode;
               return { id, email, zipcode };
           });
           // Process the extracted data
           record1.forEach(user => {
               console.log(user);
           });
       }).catch((error) => {
           console.log(error);
       });
   } catch (error) {
       console.error('Error:', error);
   }
}
fetchData();

Example 5: Fetch data of nested object attribute of response data
user.ts

export interface User {
   id: number;
   name: string;
   username: string;
   email: string;
   address: Address;
   phone: string;
   website: string;
   company: Company;
}
export interface Address {
   street: string;
   suit: string;
   city: string;
   zipcode: string;
   geo: Geo;
}
export interface Geo {
   lat: string;
   lng: string;
}
export interface Company {
   name: string;
   catchPhrase: string;
   bs: string;
}
customizedRecords.ts
export interface Records1 {
   id: number;
   email: string;
   zipcode: string;
}


main.ts
import axios from 'axios';
import { User, Address, Company } from './user';
import { Records1 } from './customizedRecords';
import { pick } from 'lodash';
async function fetchData() {
   try {
       await
           axios.get < User[] > ('https://jsonplaceholder.typicode.com/users').the
       n((response) => {
           let users: User[] = response.data;
           // Extract only specific columns
           const record1: Records1[] = users.map(user => {
               const { id, email, address } = pick(user, ['id', 'email',
                   'address']);
               const zipcode = address.zipcode;
               return { id, email, zipcode };
           });
           record1.forEach(user => {
               console.log(user);
           });
       }).catch((error) => {
           console.log(error);
       });
   } catch (error) {
       console.error('Error:', error);
   }
}
fetchData();

Example 6: With and without Interface in Axios
The raw data are transformed/organised using the interface to a well-known structure.

user.ts
export interface User {
   id: number;
   name: string;
   username: string;
   email: string;
   address: Address;
   phone: string;
   website: string;
   company: Company;
}
export interface Address {
   street: string;
   suit: string;
   city: string;
   zipcode: string;
   geo: Geo;
}
export interface Geo {
   lat: string;
   lng: string;
}
export interface Company {
   name: string;
   catchPhrase: string;
   bs: string;
}


main.ts
import axios from 'axios';
import { User } from './user';
async function fetchData() {
   try {
       //The raw data are transformed/organised using the interface
       //to a well-known structure.
       await
           axios.get < User[] > ('https://jsonplaceholder.typicode.com/users').the
       n((response) => {
           let users = response.data;
           // console.log(users.foo());
           users.forEach((user: User) => {
               // console.log(user.employeeId);
               console.log(user);
           });
       }).catch((error) => {
           console.log(error);
       });
   } catch (error) {
       console.error('Error:', error);
   }
}
fetchData();

About Author:
J
Java Developer     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.