Ways to Call a REST API from the Frontend

 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):

  1. fetch() – This is built into JavaScript. It's the easiest way. You just give it the link (URL), and it brings the data.

  2. Axios – This is a library that makes it even easier to call APIs. It handles errors better and works nicely with JSON data.

  3. In React – People use fetch() or Axios inside a function called useEffect to get data when the page loads.

  4. In Angular – There is a built-in tool called HttpClient to make API calls easily.

  5. In Vue – You can use fetch() or Axios here too.

  6. 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) 

Axios is a popular JavaScript library for making HTTP requests. It simplifies API calls and provides additional features like request cancellation and timeout handling.

Install Axios

npm install axios

Example (GET request)


import axios from 'axios'; axios.get('https://api.example.com/users') .then(response => console.log(response.data)) .catch(error => console.error('Error:', error));

Example (POST request)

axios.post('https://api.example.com/users', { name: 'John Doe', age: 25 }) .then(response => console.log(response.data)) .catch(error => console.error('Error:', error));

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)

$.ajax({ url: "https://api.example.com/users", type: "GET", success: function(response) { console.log(response); }, error: function(error) { console.error("Error:", error); } });

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

import React, { useEffect, useState } from 'react'; import axios from 'axios'; function Users() { const [users, setUsers] = useState([]); useEffect(() => { axios.get('https://api.example.com/users') .then(response => setUsers(response.data)) .catch(error => console.error(error)); }, []); return ( <div> <h2>Users List</h2> <ul> {users.map(user => ( <li key={user.id}>{user.name}</li> ))} </ul> </div> ); } export default Users;

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:

import { HttpClientModule } from '@angular/common/http'; @NgModule({ imports: [HttpClientModule] }) export class AppModule { }

Then, use it in a service:

import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class UserService { constructor(private http: HttpClient) {} getUsers() { return this.http.get('https://api.example.com/users'); } }

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)

import axios from 'axios'; export default { data() { return { users: [] }; }, mounted() { axios.get('https://api.example.com/users') .then(response => { this.users = response.data; }) .catch(error => console.error(error)); } }

Pros: Simple for Vue.js applications.
Cons: Requires Vue.js knowledge.


Post a Comment

0 Comments