JAVASCRIPT

Generic API Client Wrapper for Fetch API

Create a reusable and robust API client wrapper using JavaScript's `fetch` API, centralizing common configurations like base URLs, headers, and error handling for cleaner code.

class ApiClient {
  constructor(baseURL, defaultHeaders = {}) {
    this.baseURL = baseURL;
    this.defaultHeaders = {
      'Content-Type': 'application/json',
      ...defaultHeaders,
    };
  }

  async request(endpoint, options = {}) {
    const url = `${this.baseURL}${endpoint}`;
    const config = {
      ...options,
      headers: {
        ...this.defaultHeaders,
        ...options.headers,
      },
    };

    if (config.body && typeof config.body !== 'string') {
      config.body = JSON.stringify(config.body);
    }

    try {
      const response = await fetch(url, config);

      if (!response.ok) {
        let errorData = await response.json().catch(() => ({ message: response.statusText }));
        throw new Error(`API Error ${response.status}: ${errorData.message || response.statusText}`);
      }
      
      return await response.json();
    } catch (error) {
      console.error('API Request failed:', error);
      throw error;
    }
  }

  get(endpoint, options = {}) {
    return this.request(endpoint, { method: 'GET', ...options });
  }

  post(endpoint, data, options = {}) {
    return this.request(endpoint, { method: 'POST', body: data, ...options });
  }

  put(endpoint, data, options = {}) {
    return this.request(endpoint, { method: 'PUT', body: data, ...options });
  }

  delete(endpoint, options = {}) {
    return this.request(endpoint, { method: 'DELETE', ...options });
  }
}

// Example Usage:
// const api = new ApiClient('https://api.example.com', {
//   'Authorization': 'Bearer YOUR_AUTH_TOKEN'
// });

// async function fetchData() {
//   try {
//     const users = await api.get('/users');
//     console.log('Users:', users);

//     const newUser = await api.post('/users', { name: 'Jane Doe', email: '[email protected]' });
//     console.log('New User:', newUser);

//     await api.delete('/users/123');
//     console.log('User deleted.');
//   } catch (error) {
//     console.error('Operation failed:', error.message);
//   }
// }
// fetchData();
How it works: This snippet provides a generic `ApiClient` class to encapsulate `fetch` API calls. It centralizes the base URL, default headers (like `Content-Type`), and error handling logic. It offers convenient methods (`get`, `post`, `put`, `delete`) for common HTTP verbs, making API interactions cleaner, more consistent, and easier to manage across a web application, promoting reusability and maintainability.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs