Ways to Call a REST API from the Frontend
When we build websites, sometimes we need to get data from REST API.
There are a few simple ways to call a REST API from the frontend (browser):
-
fetch() – This is built into JavaScript. It's the easiest way. You just give it the link (URL), and it brings the data.
-
Axios – This is a library that makes it even easier to call APIs. It handles errors better and works nicely with JSON data.
-
In React – People use
fetch()
orAxios
inside a function calleduseEffect
to get data when the page loads. -
In Angular – There is a built-in tool called
HttpClient
to make API calls easily. -
In Vue – You can use
fetch()
orAxios
here too. -
jQuery (old websites) – Older sites may use jQuery’s
$.ajax()
to call APIs.
So, the most popular and easy ways are using fetch()
or Axios.
1. Using fetch()
(Native JavaScript)
The fetch
API is built into modern browsers and provides a simple way to make HTTP requests.
Example (GET request)
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: 'John Doe', age: 25 })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Example (POST request)
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: 'John Doe', age: 25 })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
✔ Pros: Native, lightweight, supports promises.
❌ Cons: No automatic timeout handling, no request cancellation.
2. Using Axios (Recommended)
Install Axios
Example (GET request)
Example (POST request)
✔ Pros: Easy to use, automatic JSON conversion, supports request cancellation.
❌ Cons: Requires additional dependency.
3. Using jQuery AJAX (Old Approach)
If your project still uses jQuery, you can use its $.ajax()
method.
Example (GET request)
✔ Pros: Works in older browsers.
❌ Cons: Heavy library, modern frameworks use fetch
or Axios
instead.
4. Using React (useEffect
Hook)
In React, the useEffect
hook is commonly used to fetch data when a component loads.
Example
✔ Pros: Works well with React components, efficient for API calls in UI.
❌ Cons: Requires React knowledge.
5. Using Angular (HttpClient
)
Angular provides HttpClient
for making API calls.
Example
First, import HttpClientModule
in app.module.ts
:
Then, use it in a service:
✔ Pros: Optimized for Angular applications.
❌ Cons: Angular-specific, requires setup.
6. Using Vue.js (fetch
or Axios)
Vue.js supports both fetch
and Axios
.
Example (Using Axios)
✔ Pros: Simple for Vue.js applications.
❌ Cons: Requires Vue.js knowledge.
0 Comments