@sapphire/fetch

Tiny wrapper around cross-fetch (for NodeJS) and window.fetch (for Browsers) for improved TypeScript and data type support

Usage no npm install needed!

<script type="module">
  import sapphireFetch from 'https://cdn.skypack.dev/@sapphire/fetch';
</script>

README

Sapphire Logo

@sapphire/fetch

Tiny wrapper around cross-fetch for improved TypeScript and data type support

GitHub codecov npm bundle size npm

Table of Contents

Description

cross-fetch is already a great library for making API calls, but because it focuses solely on bringing the Fetch API to Node.js, it doesn't provide specific error messages and handling for different return types (JSON, Buffer, plain text, etc). This is where @sapphire/fetch comes in. The syntax is more restrictive than that of cross-fetch, but that makes it consistent and easier to use in TypeScript.

Features

  • Written in TypeScript
  • Fully tested
  • Exported const enum for the common return data types.
  • Throws distinctive errors when the API returns a "not ok" status code to make them easier to understand.
  • Enforces casting the return type when requesting JSON data, to ensure your return data is strictly typed.
  • Uses cross-fetch so this package can be used in NodeJS (where it uses node-fetch) and browser (where it uses Fetch API)

Installation

You can use the following command to install this package, or replace npm install with your package manager of choice.

npm install @sapphire/fetch

Usage

Note: While this section uses import, it maps 1:1 with CommonJS' require syntax. For example, import { fetch } from '@sapphire/fetch' is the same as const { fetch } = require('@sapphire/fetch').

Note: fetch can also be imported as a default import: import fetch from '@sapphire/fetch'.

GETting JSON data

// Import the fetch function
import { 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 data
console.log(data.userId);

GETting Buffer data (images, etc.)

// Import the fetch function
import { 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 image
console.log(sapphireLogo);

POSTing JSON data

// Import the fetch function
import { 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 data
console.log(responseData);

Buy us some doughnuts

Sapphire Community is and always will be open source, even if we don't get donations. That being said, we know there are amazing people who may still want to donate just to show their appreciation. Thank you very much in advance!

We accept donations through Open Collective, Ko-fi, PayPal, Patreon and GitHub Sponsorships. You can use the buttons below to donate through your method of choice.

Donate With Address
Open Collective Click Here
Ko-fi Click Here
Patreon Click Here
PayPal Click Here

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Jeroen Claassens

πŸ’» πŸš‡ πŸ“† πŸ“– ⚠️

Antonio RomΓ‘n

πŸ’» πŸ“† πŸ‘€ ⚠️

Gryffon Bellish

πŸ’» πŸ‘€ ⚠️

Vlad Frangu

πŸ’» πŸ› πŸ‘€ πŸ““ ⚠️

Stitch07

πŸ’» πŸ“† ⚠️

depfu[bot]

🚧

allcontributors[bot]

πŸ“–

Tyler J Russell

πŸ“–

Ivan Lieder

πŸ’» πŸ›

Hezekiah Hendry

πŸ’»

Vetlix

πŸ’»

Ethan Mitchell

πŸ“–

Elliot

πŸ’»

Jurien Hamaker

πŸ’»

Charalampos Fanoulis

πŸ“–

dependabot[bot]

🚧

Kaname

πŸ’»

nandhagk

πŸ›

megatank58

πŸ’»

UndiedGamer

πŸ’»

Lioness100

πŸ“– πŸ’»

David

πŸ’»

renovate[bot]

🚧

WhiteSource Renovate

🚧

FC

πŸ’»

JΓ©rΓ©my de Saint Denis

πŸ’»

MrCube

πŸ’»

bitomic

πŸ’»

This project follows the all-contributors specification. Contributions of any kind welcome!