Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Take A QuizChallenge yourself and boost your learning! Start the quiz now to earn credits.
Take A QuizUnlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
Take A Quiz
🧭 What You’ll Learn
In this chapter, you’ll learn how to:
🧩 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:
📦 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
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
⚙️ 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:
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.
Answer:
You should understand these four primary methods:
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.
Answer:
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.
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.
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.
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.
Answer:
Refer to the API documentation provided by the API provider. It lists all
available endpoints, their expected request methods, headers, and responses.
Please log in to access this content. You will be redirected to the login page shortly.
LoginReady to take your education and career to the next level? Register today and join our growing community of learners and professionals.
Comments(0)