Skip to content

netzo.fetch()

The HTTP Client is a simple and intuitive, type-safe client that makes it easy to interact with any HTTP API, service or resource. The client is powered by JS proxies and designed to be powerful and feature-complete, yet flexible enough to handle potential edge cases common in HTTP APIs.

  • Intuitive: access any path via simple chain or bracket syntax
  • Complete: use any HTTP method by chaining it to the path
  • Lightweight: ships less than 100 lines of code (generates client dynamically)
  • Robust: Strongly typed and ability to type responses dynamically
  • Isomorphic: runs in the frontend (browser) and backend (Deno and Node.js)
ts
const client = netzo.fetch()

Path segment chaining

An instance of the HTTP client is a proxy that allows you to access the API endpoints as properties. For example, if the API has an endpoint /todos you can access it by chaining the individual path segments or path parameters by a dot. If using TypeScript, you can even type the response using the <> syntax.

ts
// GET request to <baseURL>/users
const users = await client.users.get<UserResponse>()

// For GET request you can add search params
// <baseURL>/users?search=john
const users = await client.users.get<UserResponse>({ search: 'john' })

To include dynamic API path segments, you have two options:

ts
// Typed GET request to <baseURL>/users/1
const userId = 1
// … using the chain syntax:
const user = await client.users(userId).get<UserResponse>()
// … or the bracket syntax:
const user = await client.users[`${userId}`].get<UserResponse>()

HTTP request methods

Add the appropriate method to the end of your API call. The following methods are supported:

  • get()
  • post()
  • put()
  • delete()
  • patch()

Payload requests

For HTTP request methods supporting a payload, add it to the method call:

ts
// POST request to <baseURL>/users
const response = await client.users.post({ name: 'foo' })

Default options for netzo.fetch()

ts
const client = await netzo.fetch({
  baseURL: 'https://jsonplaceholder.typicode.com',
  async onRequestError({ request, options, error }) {
    console.log('[fetch request error]', request, error)
  },
  async onResponseError({ request, options, error }) {
    console.log('[fetch response error]', request, error)
  },
})

Override Default Options

You can add/overwrite netzo.fetch() options on a method-level:

ts
const response = await client.users.get({
  headers: {
    'Cache-Control': 'no-cache'
  }
})

Type Definitions

Refer to http/types.ts for the type definitions of this module.

netzo.fetch() has loaded