All Projects → sanity-io → get-it

sanity-io / get-it

Licence: MIT license
Composable HTTP request library for node and browsers

Programming Languages

javascript
184084 projects - #8 most used programming language
typescript
32286 projects

Projects that are alternatives of or similar to get-it

Phin
Node HTTP client
Stars: ✭ 449 (+2263.16%)
Mutual labels:  http-client, request
oh-my-request
🔮 simple request library by java8
Stars: ✭ 41 (+115.79%)
Mutual labels:  http-client, request
Urllib
Request HTTP(s) URLs in a complex world
Stars: ✭ 600 (+3057.89%)
Mutual labels:  http-client, request
httper
An asynchronous HTTP(S) client built on top of hyper.
Stars: ✭ 16 (-15.79%)
Mutual labels:  http-client, request
Rxios
A RxJS wrapper for axios
Stars: ✭ 119 (+526.32%)
Mutual labels:  http-client, request
Gretchen
Making fetch happen in TypeScript.
Stars: ✭ 301 (+1484.21%)
Mutual labels:  http-client, request
Ky
🌳 Tiny & elegant JavaScript HTTP client based on the browser Fetch API
Stars: ✭ 7,047 (+36989.47%)
Mutual labels:  http-client, request
go-axios
HTTP Request package for golang.
Stars: ✭ 29 (+52.63%)
Mutual labels:  http-client, request
Http Client
A high-performance, high-stability, cross-platform HTTP client.
Stars: ✭ 86 (+352.63%)
Mutual labels:  http-client, request
Oh My Request
🔮 simple request library by java8
Stars: ✭ 44 (+131.58%)
Mutual labels:  http-client, request
axios-for-observable
A RxJS wrapper for axios, same api as axios absolutely
Stars: ✭ 13 (-31.58%)
Mutual labels:  http-client, request
Wretch
A tiny wrapper built around fetch with an intuitive syntax. 🍬
Stars: ✭ 2,285 (+11926.32%)
Mutual labels:  http-client, request
electron-request
Zero-dependency, Lightweight HTTP request client for Electron or Node.js
Stars: ✭ 45 (+136.84%)
Mutual labels:  http-client, request
Ky Universal
Use Ky in both Node.js and browsers
Stars: ✭ 421 (+2115.79%)
Mutual labels:  http-client, request
request-extra
⚡️ Extremely stable HTTP request module built on top of libcurl with retries, timeouts and callback API
Stars: ✭ 14 (-26.32%)
Mutual labels:  http-client, request
Gout
gout to become the Swiss Army Knife of the http client @^^@---> gout 是http client领域的瑞士军刀,小巧,强大,犀利。具体用法可看文档,如使用迷惑或者API用得不爽都可提issues
Stars: ✭ 749 (+3842.11%)
Mutual labels:  http-client, request
puzzle-warden
🔌 Improved http client with epic features for creating fast and scalable applications.
Stars: ✭ 41 (+115.79%)
Mutual labels:  http-client, request
centra
Core Node.js HTTP client
Stars: ✭ 52 (+173.68%)
Mutual labels:  http-client, request
Create Request
Apply interceptors to `fetch` and create a custom request function.
Stars: ✭ 34 (+78.95%)
Mutual labels:  http-client, request
Baseokhttpv3
🔥OkHttp的二次封装库,提供各种快速使用方法以及更为方便的扩展功能。提供更高效的Json请求和解析工具以及文件上传下载封装,HTTPS和Cookie操作也更得心应手。
Stars: ✭ 121 (+536.84%)
Mutual labels:  http-client, request

get-it

npm versionBuild Status

Generic HTTP request library for node.js (>= 12) and browsers (IE9 and newer)

Motivation

We wanted an HTTP request library that worked transparently in Node.js and browsers with a small browser bundle footprint.

To be able to use the same library in a range of different applications with varying requirements, but still keep the bundle size down, we took inspiration from http-client which cleverly composes functionality into the client.

Features

Using a middleware approach, get-it has the following feature set:

  • Promise, observable and low-level event-emitter patterns
  • Automatic retrying with customizable number of attempts and filtering functionality
  • Cancellation of requests
  • Configurable connect/socket timeouts
  • Automatic parsing of JSON responses
  • Automatic stringifying of JSON request bodies
  • Automatic gzip unwrapping in Node
  • Automatically prepend base URL
  • Automatically follow redirects (configurable number of retries)
  • Upload/download progress events
  • Treat HTTP status codes >=400 as errors
  • Debug requests with environment variables/localStorage setting

Usage

How get-it behaves depends on which middleware you've loaded, but common to all approaches is the setup process.

// Require the core get-it package, which is used to generate a requester
const getIt = require('get-it')

// And require whatever middleware you want to use
const base = require('get-it/lib/middleware/base')
const jsonResponse = require('get-it/lib/middleware/jsonResponse')
const promise = require('get-it/lib/middleware/promise')

// Now compose the middleware you want to use
const request = getIt([base('https://api.your.service/v1'), jsonResponse()])

// You can also register middleware using `.use(middleware)`
request.use(promise())

// Now you're ready to use the requester:
request({url: '/projects'})
  .then(response => console.log(response.body))
  .catch(err => console.error(err))

In most larger projects, you'd probably make a httpClient.js or similar, where you would instantiate the requester and export it for other modules to reuse.

Options

  • url - URL to the resource you want to reach.
  • method - HTTP method to use for request. Default: GET, unless a body is provided, in which case the default is POST.
  • headers - Object of HTTP headers to send. Note that cross-origin requests in IE9 will not be able to set these headers.
  • body - The request body. If the jsonRequest middleware is used, it will serialize to a JSON string before sending. Otherwise, it tries to send whatever is passed to it using the underlying adapter. Supported types:
    • Browser: string, ArrayBufferView, Blob, Document, FormData (deprecated: ArrayBuffer)
    • Node: string, buffer, ReadStream
  • bodySize - Size of body, in bytes. Only used in Node when passing a ReadStream as body, in order for progress events to emit status on upload progress.
  • timeout - Timeout in millisecond for the request. Takes an object with connect and socket properties.
  • maxRedirects - Maximum number of redirects to follow before giving up. Note that this is only used in Node, as browsers have built-in redirect handling which cannot be adjusted. Default: 5
  • rawBody - Set to true to return the raw value of the response body, instead of a string. The type returned differs based on the underlying adapter:
    • Browser: ArrayBuffer
    • Node: Buffer

Return values

By default, get-it will return an object of single-channel event emitters. This is done in order to provide a low-level API surface that others can build upon, which is what the promise and observable middlewares do. Unless you really know what you're doing, you'll probably want to use those middlewares.

Response objects

get-it does not expose the low-level primitives such as the XMLHttpRequest or http.IncomingMessage instances. Instead, it provides a response object with the following properties:

{
  // string (ArrayBuffer or Buffer if `rawBody` is set to `true`)
  body: 'Response body'
  url: 'http://foo.bar/baz',
  method: 'GET',
  statusCode: 200,
  statusMessage: 'OK',
  headers: {
    'Date': 'Fri, 09 Dec 2016 14:55:32 GMT',
    'Cache-Control': 'public, max-age=120'
  }
}

Promise API

For the most part, you simply have to register the middleware and you should be good to go. Sometimes you only need the response body, in which case you can set the onlyBody option to true. Otherwise the promise will be resolved with the response object mentioned earlier.

const getIt = require('get-it')
const promise = require('get-it/lib/middleware/promise')
const request = getIt([promise({onlyBody: true})])

request({url: 'http://foo.bar/api/projects'})
  .then(projects => console.log(projects))
  .catch(err => console.error(err))

If you are targetting older browsers that do not have a global Promise implementation, you must register one globally using a polyfill such as es6-promise:

require('es6-promise/auto')

const promise = require('get-it/lib/middleware/promise')
const request = getIt([promise()])

Cancelling promise-based requests

With the Promise API, you can cancel requests using a cancel token. This API is based on the Cancelable Promises proposal, which was at Stage 1 before it was withdrawn.

You can create a cancel token using the CancelToken.source factory as shown below:

const promise = require('get-it/lib/middleware/promise')
const request = getIt([promise()])

const source = promise.CancelToken.source()

request
  .get({
    url: 'http://foo.bar/baz',
    cancelToken: source.token
  })
  .catch(err => {
    if (promise.isCancel(err)) {
      console.log('Request canceled', err.message)
    } else {
      // handle error
    }
  })

// Cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user')

Observable API

The observable API requires you to pass an Observable-implementation that you want to use. Optionally, you can register it under the global Observable, but this is not recommended.

const getIt = require('get-it')
const observable = require('get-it/lib/middleware/observable')
const request = getIt()

request.use(
  observable({
    implementation: require('zen-observable')
  })
)

const observer = request({url: 'http://foo.bar/baz'})
  .filter(ev => ev.type === 'response')
  .subscribe({
    next: res => console.log(res.body),
    error: err => console.error(err)
  })

// If you want to cancel the request, simply unsubscribe:
observer.unsubscribe()

It's important to note that the observable middleware does not only emit response objects, but also progress events. You should always filter to specify what you're interested in receiving. Every emitted value has a type property.

Upcoming features

  • Developer-friendly assertions that are stripped in production to reduce bundle size and performance
  • Authentication (basic)
  • Stream response middleware?

Prior art

This module was inspired by the great work of others:

License

MIT-licensed. See LICENSE.

Release new version

Run the "CI & Release" workflow. Make sure to select the main branch and check "Release new version".

Semantic release will only release on configured branches, so it is safe to run release on any branch.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].