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

8.96K 0 1 0 0
3.00   (1 )

📘 Chapter 2: Making API Calls with JavaScript — fetch() and axios

🧭 What You’ll Learn

By the end of this chapter, you’ll understand:

  • How to make HTTP requests using the native fetch() API
  • How to simplify your API code using axios
  • The structure of a typical API request and response
  • Error handling techniques in both methods
  • The differences between fetch and axios
  • Real-world usage patterns with code samples
  • When and why to use async/await

🌐 What Is an HTTP Request?

An HTTP request is a message sent by the client (your front-end code) to a server to:

  • Retrieve data (GET)
  • Send data (POST)
  • Update data (PUT / PATCH)
  • Delete data (DELETE)

The response usually comes back in JSON format.


🔹 Using the Native fetch() API

fetch() is built into modern browsers and returns a Promise, making it ideal for asynchronous operations.

Syntax

js

 

fetch(url, {

  method: 'GET',

  headers: {

    'Content-Type': 'application/json',

    // 'Authorization': 'Bearer yourToken'

  },

  body: JSON.stringify(data) // Only for POST, PUT, PATCH

})


📌 Basic GET Example

js

 

fetch('https://jsonplaceholder.typicode.com/posts')

  .then(res => res.json())

  .then(data => console.log(data))

  .catch(err => console.error('Error:', err));


📌 POST Example

js

 

const postData = {

  title: 'Hello World',

  body: 'This is a post.',

  userId: 1

};

 

fetch('https://jsonplaceholder.typicode.com/posts', {

  method: 'POST',

  headers: {

    'Content-Type': 'application/json'

  },

  body: JSON.stringify(postData)

})

  .then(res => res.json())

  .then(data => console.log(data));


🔄 Using async/await with fetch()

js

 

async function fetchPosts() {

  try {

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

    const data = await res.json();

    console.log(data);

  } catch (error) {

    console.error('Fetch Error:', error);

  }

}


🚀 Using axios for API Calls

axios is a promise-based HTTP client library that simplifies many aspects of working with APIs.

📦 Install

bash

 

npm install axios


GET Request

js

 

import axios from 'axios';

 

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

  .then(res => console.log(res.data))

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


POST Request

js

 

axios.post('https://jsonplaceholder.typicode.com/posts', {

  title: 'New Post',

  body: 'Post content here',

  userId: 1

})

  .then(res => console.log(res.data))

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


With async/await

js

 

async function createPost() {

  try {

    const res = await axios.post('https://jsonplaceholder.typicode.com/posts', {

      title: 'Async Post',

      body: 'Made with async/await',

      userId: 1

    });

    console.log(res.data);

  } catch (err) {

    console.error('Axios error:', err);

  }

}


📊 fetch() vs axios Comparison

Feature

fetch()

axios

Built-in

Yes

No (install separately)

Automatically parses JSON

.json() needed

res.data is parsed

Handles request timeout

Requires manual setup

Built-in

Request cancellation

Not easy

With AbortController

Error handling

Manual for status codes

Built-in .catch() handles all

Interceptors (global config)

Yes


🧠 Understanding API Request Structure

Parts of an HTTP request:

  • URL – The endpoint you want to call
  • Method – GET, POST, PUT, DELETE, etc.
  • Headers – Auth tokens, content type
  • Body – Data (only for write operations)

📘 Example

js

 

fetch('https://api.site.com/posts', {

  method: 'POST',

  headers: {

    'Authorization': 'Bearer token123',

    'Content-Type': 'application/json'

  },

  body: JSON.stringify({ title: 'Post Title' })

})


️ Error Handling Best Practices

With fetch():

js

 

fetch('https://api.site.com/data')

  .then(res => {

    if (!res.ok) throw new Error('Network response not ok');

    return res.json();

  })

  .catch(err => console.error('Fetch failed:', err));

With axios:

js

 

axios.get('https://api.site.com/data')

  .catch(error => {

    if (error.response) {

      console.error('Server responded with:', error.response.status);

    } else {

      console.error('Network or setup error:', error.message);

    }

  });


🧩 Real-World Scenarios

Scenario

Example API Action

Form submission

axios.post('/api/register', formData)

Infinite scroll or pagination

fetch('/api/posts?page=2')

File upload

Use multipart/form-data with axios

Authentication

Attach token in Authorization header

Data refresh on interval

Polling using setInterval() with fetch()


🧰 Handling Headers and Tokens

Setting headers manually:

js

 

fetch('/api/user', {

  headers: {

    'Authorization': 'Bearer YOUR_TOKEN',

    'Content-Type': 'application/json'

  }

});

With axios globally:

js

 

axios.defaults.headers.common['Authorization'] = 'Bearer YOUR_TOKEN';


🧼 Canceling Requests (axios only)

js

 

const controller = new AbortController();

 

axios.get('/api/data', { signal: controller.signal });

 

controller.abort(); // Cancel the request


🎨 UI Tips for API Integration

  • Use loading spinners while waiting for data
  • Disable buttons during API operations
  • Handle error messages gracefully
  • Provide retry options when a request fails

Summary

In this chapter, you’ve learned how to:

  • Use fetch() and axios for GET, POST, and other API calls
  • Use async/await for cleaner syntax
  • Handle errors effectively
  • Compare the strengths of fetch() vs axios
  • Pass headers, handle tokens, and structure API requests properly
  • Use HTTP methods and status codes to manage CRUD operations


Up next: Chapter 3: Authentication and Secure API Access – where you'll handle token storage, protected endpoints, and secure API communication.

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.