Skip to main content

Using Fetch

Introduction

Sapphire's fetch package, @sapphire/fetch is a small wrapper around cross-fetch so it will work in both the web browser and the native node.js environment.

Installation

npm install @sapphire/fetch

Usage

GETting JSON data
// Import the fetch functionimport { fetch, FetchResultTypes } from '@sapphire/fetch';interface JsonPlaceholderResponse {  userId: number;  id: number;  title: string;  completed: boolean;}// Fetch the data. No need to call `.json()` after making the request!const data = await fetch<JsonPlaceholderResponse>(  'https://jsonplaceholder.typicode.com/todos/1',  FetchResultTypes.JSON);// Do something with the dataconsole.log(data.userId);
GETting Buffer data
// Import the fetch functionimport { fetch, FetchResultTypes } from '@sapphire/fetch';// Fetch the data. No need to call `.buffer()` after making the request!const sapphireLogo = await fetch('https://github.com/sapphiredev.png', FetchResultTypes.Buffer);// sapphireLogo is the `Buffer` of the imageconsole.log(sapphireLogo);
POSTing JSON data
// Import the fetch functionimport { fetch, FetchResultTypes, FetchMethods } from '@sapphire/fetch';// Fetch the data. No need to call `.json()` after making the request!const responseData = await fetch(  'https://jsonplaceholder.typicode.com/todos',  {    method: FetchMethods.Post,    headers: {      'Content-Type': 'application/json'    },    body: JSON.stringify({      name: 'John Doe'    })  },  FetchResultTypes.JSON);// Do something with the response dataconsole.log(responseData);