API Integration for Front-End Developers: A Practical Guide to Connecting Interfaces and Data

8.29K 0 1 0 0
3.00   (1 )

📘 Chapter 5: API Integration in Modern Frameworks (React, Vue, Angular)

🧭 What You’ll Learn

In this chapter, you’ll learn how to:

  • Make API calls in React, Vue, and Angular
  • Manage loading, error, and success states
  • Use hooks in React, composition API in Vue, and services in Angular
  • Implement token-based authentication with global headers
  • Organize API logic with best practices for each framework

🧩 Why Frameworks Need APIs

Whether you're building a to-do app, admin dashboard, or an e-commerce site—every serious application needs data. And that data usually comes from an external or internal API.

Unlike vanilla JavaScript, modern frameworks offer:

  • Lifecycle hooks (e.g., useEffect, mounted, ngOnInit)
  • Reusable components
  • Centralized state or data services
  • Routing for protected paths

📦 React: API Integration

React uses hooks like useEffect and useState to manage data-fetching logic.

🔧 Example: Fetch Posts in React

jsx

 

import { useEffect, useState } from 'react';

import axios from 'axios';

 

function Posts() {

  const [posts, setPosts] = useState([]);

  const [loading, setLoading] = useState(true);

 

  useEffect(() => {

    axios.get('https://jsonplaceholder.typicode.com/posts')

      .then((res) => setPosts(res.data))

      .catch((err) => console.error(err))

      .finally(() => setLoading(false));

  }, []);

 

  if (loading) return <p>Loading...</p>;

 

  return (

    <ul>

      {posts.map(post => (

        <li key={post.id}>{post.title}</li>

      ))}

    </ul>

  );

}


🧠 React Best Practices

  • Extract API logic into custom hooks (usePosts.js)
  • Use useContext or libraries like Redux for global token storage
  • Handle tokens in axios default headers:

js

 

axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;


🖼 Vue 3: API Integration

Vue 3 uses the Composition API (setup(), ref(), onMounted()) or the Options API (data, mounted, methods).

🔧 Example: Fetch Data with Composition API

vue

 

<template>

  <ul v-if="!loading">

    <li v-for="post in posts" :key="post.id">{{ post.title }}</li>

  </ul>

  <p v-else>Loading...</p>

</template>

 

<script setup>

import { ref, onMounted } from 'vue';

import axios from 'axios';

 

const posts = ref([]);

const loading = ref(true);

 

onMounted(async () => {

  try {

    const res = await axios.get('https://jsonplaceholder.typicode.com/posts');

    posts.value = res.data;

  } catch (err) {

    console.error(err);

  } finally {

    loading.value = false;

  }

});

</script>


🧠 Vue Best Practices

  • Use ref() for reactive values
  • Use Pinia or Vuex for global token/state management
  • Place API calls in reusable composables or store actions

️ Angular: API Integration

Angular uses services and dependency injection for centralized API logic.

🔧 Create a Service

bash

 

ng generate service api

🔧 api.service.ts

ts

 

import { Injectable } from '@angular/core';

import { HttpClient } from '@angular/common/http';

 

@Injectable({ providedIn: 'root' })

export class ApiService {

  constructor(private http: HttpClient) {}

 

  getPosts() {

    return this.http.get('https://jsonplaceholder.typicode.com/posts');

  }

}


🔧 Use Service in Component

ts

 

import { Component, OnInit } from '@angular/core';

import { ApiService } from './api.service';

 

@Component({

  selector: 'app-posts',

  template: `

    <div *ngIf="loading">Loading...</div>

    <ul *ngIf="!loading">

      <li *ngFor="let post of posts">{{ post.title }}</li>

    </ul>

  `

})

export class PostsComponent implements OnInit {

  posts: any[] = [];

  loading = true;

 

  constructor(private api: ApiService) {}

 

  ngOnInit() {

    this.api.getPosts().subscribe({

      next: (res: any) => this.posts = res,

      error: (err) => console.error(err),

      complete: () => this.loading = false

    });

  }

}


🔐 Handling Authentication Tokens

Framework

How to Add Auth Header Globally

React

axios.defaults.headers.common['Authorization'] = …

Vue

axios.interceptors.request.use() or composable

Angular

Use HttpInterceptor with HttpClientModule

Angular Interceptor Example

ts

 

@Injectable()

export class AuthInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler) {

    const token = localStorage.getItem('token');

    const authReq = req.clone({

      headers: req.headers.set('Authorization', `Bearer ${token}`)

    });

    return next.handle(authReq);

  }

}

Register it in app.module.ts under providers.


🔃 Common API Lifecycle Hooks

Framework

API Lifecycle Method

React

useEffect()

Vue

onMounted()

Angular

ngOnInit()


📄 CRUD Operation Table (Across Frameworks)

Action

React

Vue

Angular

Read (GET)

axios.get() in useEffect

onMounted() + axios.get()

apiService.getPosts()

Create (POST)

Form + axios.post()

Form + axios.post()

apiService.createPost()

Update (PUT)

axios.put() with form

axios.put() + ref()

apiService.updatePost()

Delete

axios.delete()

axios.delete()

apiService.deletePost()


🧠 API Structure Best Practices

Tip

Description

Centralize API logic

Use services/hooks for reusability

Avoid repetition

Share request logic in helpers or modules

Handle loading/errors uniformly

Create wrappers or utility states

Token management

Store securely and pass via headers


Summary

You’ve now learned how to:


  • Integrate APIs in React, Vue, and Angular apps
  • Handle asynchronous logic with each framework's lifecycle method
  • Send tokens in headers securely
  • Organize code using services, hooks, or composables
  • Structure CRUD logic in components cleanly

Back

FAQs


❓1. What is API integration in front-end development?

Answer:
API integration in front-end development refers to the process of connecting the user interface (UI) of a website or application with external data sources or back-end services using APIs (Application Programming Interfaces), typically through HTTP requests.

❓2. Which HTTP methods do I need to know for API integration?

Answer:
You should understand these four primary methods:

  • GET – to retrieve data
  • POST – to send new data
  • PUT/PATCH – to update existing data
  • DELETE – to remove data

❓3. What’s the difference between fetch and axios?

Answer:
Both are used to make HTTP requests, but axios is a third-party library that offers a simpler API, automatic JSON parsing, request cancellation, and better error handling compared to the native fetch.

❓4. What does a status code like 404 or 500 mean during API calls?

Answer:

  • 404 Not Found means the requested resource doesn’t exist.
  • 500 Internal Server Error indicates a server-side issue.
    Other common codes include 200 (OK), 401 (Unauthorized), and 400 (Bad Request).

❓5. What is CORS and how does it affect API integration?

Answer:
CORS (Cross-Origin Resource Sharing) is a security feature that restricts web pages from making requests to a different domain. If not configured properly on the API server, your front-end app may receive a CORS error when trying to fetch data.

❓6. How do I authenticate users when calling protected APIs?

Answer:
Most APIs use token-based authentication (e.g., Bearer tokens or JWTs). After login, the token is stored (in localStorage or cookies) and sent in the Authorization header of future requests.

❓7. Can I make API calls from static HTML/JavaScript files?

Answer:
Yes, you can use the native fetch() method or axios in a <script> tag, but beware of CORS issues and avoid exposing sensitive API keys in client-side code.

❓8. What should I do if an API request fails?

Answer:
Use try/catch blocks or .catch() with fetch/axios to gracefully handle errors. Also show user feedback (e.g., error messages or retry buttons) when something goes wrong.

❓9. How do I know which API endpoint to use?

Answer:
Refer to the API documentation provided by the API provider. It lists all available endpoints, their expected request methods, headers, and responses.

❓10. What tools can I use to test APIs before integrating them?

Answer:
You can use tools like Postman, Insomnia, or browser DevTools to send test requests and inspect responses before writing your front-end code.