typescript

Generic Fetch Wrapper

Type-safe HTTP client with generics and error handling

Tarun Sharma
Tarun SharmaJanuary 15, 2024 · 1 min read · Last Updated:
interface ApiError {
  message: string;
  status: number;
}

async function fetchJson<T>(url: string, options?: RequestInit): Promise<T> {
  const response = await fetch(url, {
    headers: { 'Content-Type': 'application/json' },
    ...options,
  });

  if (!response.ok) {
    const error: ApiError = {
      message: response.statusText,
      status: response.status,
    };
    throw error;
  }

  return response.json() as Promise<T>;
}

// HTTP methods
const api = {
  get: <T>(url: string) => fetchJson<T>(url),

  post: <T, B>(url: string, body: B) =>
    fetchJson<T>(url, {
      method: 'POST',
      body: JSON.stringify(body),
    }),

  put: <T, B>(url: string, body: B) =>
    fetchJson<T>(url, {
      method: 'PUT',
      body: JSON.stringify(body),
    }),

  delete: <T>(url: string) => fetchJson<T>(url, { method: 'DELETE' }),
};

Usage

interface User {
  id: number;
  name: string;
}

const user = await api.get<User>('/api/users/1');
const newUser = await api.post<User, Omit<User, 'id'>>('/api/users', {
  name: 'John',
});

This page is open source. Noticed a typo? Or something unclear?
Improve this page on GitHub


Tarun Sharma

Written byTarun Sharma
Full-stack developer and tech educator with 10+ years of experience building scalable applications. Passionate about Node.js, NestJS, React, and cloud technologies. Creator of 50+ courses on Udemy and active YouTube educator helping developers level up their skills.
Connect

Is this page helpful?

Related VideosView All

Stack Overflow Clone - APIs Integration Redux Toolkit [Closure] - App Demo #05

Become Ninja Developer - API security Best Practices with Node JS Packages #15

Nest JS Microservices using HTTP Gateway and Redis Services (DEMO) #nestjs #microservices #16