UNPKG

35.1 kBMarkdownView Raw
1<div align="center">
2 <br>
3 <br>
4 <img width="360" src="media/logo.svg" alt="Got">
5 <br>
6 <br>
7 <br>
8 <p align="center">Huge thanks to <a href="https://moxy.studio"><img src="https://sindresorhus.com/assets/thanks/moxy-logo.svg" width="150"></a> for sponsoring me!
9 </p>
10 <br>
11 <br>
12</div>
13
14> Simplified HTTP requests
15
16[![Build Status: Linux](https://travis-ci.org/sindresorhus/got.svg?branch=master)](https://travis-ci.org/sindresorhus/got) [![Coverage Status](https://coveralls.io/repos/github/sindresorhus/got/badge.svg?branch=master)](https://coveralls.io/github/sindresorhus/got?branch=master) [![Downloads](https://img.shields.io/npm/dm/got.svg)](https://npmjs.com/got) [![Install size](https://packagephobia.now.sh/badge?p=got)](https://packagephobia.now.sh/result?p=got)
17
18Got is a human-friendly and powerful HTTP request library.
19
20It was created because the popular [`request`](https://github.com/request/request) package is bloated: [![Install size](https://packagephobia.now.sh/badge?p=request)](https://packagephobia.now.sh/result?p=request)
21
22Got is for Node.js. For browsers, we recommend [Ky](https://github.com/sindresorhus/ky).
23
24
25## Highlights
26
27- [Promise & stream API](#api)
28- [Request cancelation](#aborting-the-request)
29- [RFC compliant caching](#cache-adapters)
30- [Follows redirects](#followredirect)
31- [Retries on failure](#retry)
32- [Progress events](#onuploadprogress-progress)
33- [Handles gzip/deflate](#decompress)
34- [Timeout handling](#timeout)
35- [Errors with metadata](#errors)
36- [JSON mode](#json)
37- [WHATWG URL support](#url)
38- [Electron support](#useelectronnet)
39- [Instances with custom defaults](#instances)
40- [Composable](advanced-creation.md#merging-instances)
41- [Used by ~2000 packages and ~500K repos](https://github.com/sindresorhus/got/network/dependents)
42- Actively maintained
43
44[See how Got compares to other HTTP libraries](#comparison)
45
46
47## Install
48
49```
50$ npm install got
51```
52
53<a href="https://www.patreon.com/sindresorhus">
54 <img src="https://c5.patreon.com/external/logo/become_a_patron_button@2x.png" width="160">
55</a>
56
57
58## Usage
59
60```js
61const got = require('got');
62
63(async () => {
64 try {
65 const response = await got('sindresorhus.com');
66 console.log(response.body);
67 //=> '<!doctype html> ...'
68 } catch (error) {
69 console.log(error.response.body);
70 //=> 'Internal server error ...'
71 }
72})();
73```
74
75###### Streams
76
77```js
78const fs = require('fs');
79const got = require('got');
80
81got.stream('sindresorhus.com').pipe(fs.createWriteStream('index.html'));
82
83// For POST, PUT, and PATCH methods `got.stream` returns a `stream.Writable`
84fs.createReadStream('index.html').pipe(got.stream.post('sindresorhus.com'));
85```
86
87
88### API
89
90It's a `GET` request by default, but can be changed by using different methods or in the `options`.
91
92#### got(url, [options])
93
94Returns a Promise for a [`response` object](#response) or a [stream](#streams-1) if `options.stream` is set to true.
95
96##### url
97
98Type: `string` `Object`
99
100The URL to request, as a string, a [`https.request` options object](https://nodejs.org/api/https.html#https_https_request_options_callback), or a [WHATWG `URL`](https://nodejs.org/api/url.html#url_class_url).
101
102Properties from `options` will override properties in the parsed `url`.
103
104If no protocol is specified, it will default to `https`.
105
106##### options
107
108Type: `Object`
109
110Any of the [`https.request`](https://nodejs.org/api/https.html#https_https_request_options_callback) options.
111
112###### baseUrl
113
114Type: `string` `Object`
115
116When specified, `url` will be prepended by `baseUrl`.<br>
117If you specify an absolute URL, it will skip the `baseUrl`.
118
119Very useful when used with `got.extend()` to create niche-specific Got instances.
120
121Can be a string or a [WHATWG `URL`](https://nodejs.org/api/url.html#url_class_url).
122
123Backslash at the end of `baseUrl` and at the beginning of the `url` argument is optional:
124
125```js
126await got('hello', {baseUrl: 'https://example.com/v1'});
127//=> 'https://example.com/v1/hello'
128
129await got('/hello', {baseUrl: 'https://example.com/v1/'});
130//=> 'https://example.com/v1/hello'
131
132await got('/hello', {baseUrl: 'https://example.com/v1'});
133//=> 'https://example.com/v1/hello'
134```
135
136###### headers
137
138Type: `Object`<br>
139Default: `{}`
140
141Request headers.
142
143Existing headers will be overwritten. Headers set to `null` will be omitted.
144
145###### stream
146
147Type: `boolean`<br>
148Default: `false`
149
150Returns a `Stream` instead of a `Promise`. This is equivalent to calling `got.stream(url, [options])`.
151
152###### body
153
154Type: `string` `Buffer` `stream.Readable` [`form-data` instance](https://github.com/form-data/form-data)
155
156*If you provide this option, `got.stream()` will be read-only.*
157
158The body that will be sent with a `POST` request.
159
160If present in `options` and `options.method` is not set, `options.method` will be set to `POST`.
161
162The `content-length` header will be automatically set if `body` is a `string` / `Buffer` / `fs.createReadStream` instance / [`form-data` instance](https://github.com/form-data/form-data), and `content-length` and `transfer-encoding` are not manually set in `options.headers`.
163
164###### cookieJar
165
166Type: [`tough.CookieJar` instance](https://github.com/salesforce/tough-cookie#cookiejar)
167
168Cookie support. You don't have to care about parsing or how to store them. [Example.](#cookies)
169
170**Note:** `options.headers.cookie` will be overridden.
171
172###### encoding
173
174Type: `string` `null`<br>
175Default: `'utf8'`
176
177[Encoding](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings) to be used on `setEncoding` of the response data. If `null`, the body is returned as a [`Buffer`](https://nodejs.org/api/buffer.html) (binary data).
178
179###### form
180
181Type: `boolean`<br>
182Default: `false`
183
184*If you provide this option, `got.stream()` will be read-only.*
185
186If set to `true` and `Content-Type` header is not set, it will be set to `application/x-www-form-urlencoded`.
187
188`body` must be a plain object. It will be converted to a query string using [`(new URLSearchParams(object)).toString()`](https://nodejs.org/api/url.html#url_constructor_new_urlsearchparams_obj).
189
190###### json
191
192Type: `boolean`<br>
193Default: `false`
194
195*If you use `got.stream()`, this option will be ignored.*
196
197If set to `true` and `Content-Type` header is not set, it will be set to `application/json`.
198
199Parse response body with `JSON.parse` and set `accept` header to `application/json`. If used in conjunction with the `form` option, the `body` will the stringified as querystring and the response parsed as JSON.
200
201`body` must be a plain object or array and will be stringified.
202
203###### query
204
205Type: `string` `Object` [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
206
207Query string object that will be added to the request URL. This will override the query string in `url`.
208
209###### timeout
210
211Type: `number` `Object`
212
213Milliseconds to wait for the server to end the response before aborting the request with [`got.TimeoutError`](#gottimeouterror) error (a.k.a. `request` property). By default, there's no timeout.
214
215This also accepts an `object` with the following fields to constrain the duration of each phase of the request lifecycle:
216
217- `lookup` starts when a socket is assigned and ends when the hostname has been resolved. Does not apply when using a Unix domain socket.
218- `connect` starts when `lookup` completes (or when the socket is assigned if lookup does not apply to the request) and ends when the socket is connected.
219- `secureConnect` starts when `connect` completes and ends when the handshaking process completes (HTTPS only).
220- `socket` starts when the socket is connected. See [request.setTimeout](https://nodejs.org/api/http.html#http_request_settimeout_timeout_callback).
221- `response` starts when the request has been written to the socket and ends when the response headers are received.
222- `send` starts when the socket is connected and ends with the request has been written to the socket.
223- `request` starts when the request is initiated and ends when the response's end event fires.
224
225###### retry
226
227Type: `number` `Object`<br>
228Default:
229- retries: `2`
230- methods: `GET` `PUT` `HEAD` `DELETE` `OPTIONS` `TRACE`
231- statusCodes: [`408`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/408) [`413`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/413) [`429`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429) [`500`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500) [`502`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/502) [`503`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/503) [`504`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504)
232- maxRetryAfter: `undefined`
233
234An object representing `retries`, `methods`, `statusCodes` and `maxRetryAfter` fields for the time until retry, allowed methods, allowed status codes and maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time.
235
236If `maxRetryAfter` is set to `undefined`, it will use `options.timeout`.<br>
237If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will cancel the request.
238
239Delays between retries counts with function `1000 * Math.pow(2, retry) + Math.random() * 100`, where `retry` is attempt number (starts from 0).
240
241The `retries` property can be a `number` or a `function` with `retry` and `error` arguments. The function must return a delay in milliseconds (`0` return value cancels retry).
242
243**Note:** It retries only on the specified methods, status codes, and on these network errors:
244- `ETIMEDOUT`: One of the [timeout](#timeout) limits were reached.
245- `ECONNRESET`: Connection was forcibly closed by a peer.
246- `EADDRINUSE`: Could not bind to any free port.
247- `ECONNREFUSED`: Connection was refused by the server.
248- `EPIPE`: The remote side of the stream being written has been closed.
249
250###### followRedirect
251
252Type: `boolean`<br>
253Default: `true`
254
255Defines if redirect responses should be followed automatically.
256
257Note that if a `303` is sent by the server in response to any request type (`POST`, `DELETE`, etc.), Got will automatically request the resource pointed to in the location header via `GET`. This is in accordance with [the spec](https://tools.ietf.org/html/rfc7231#section-6.4.4).
258
259###### decompress
260
261Type: `boolean`<br>
262Default: `true`
263
264Decompress the response automatically. This will set the `accept-encoding` header to `gzip, deflate` unless you set it yourself.
265
266If this is disabled, a compressed response is returned as a `Buffer`. This may be useful if you want to handle decompression yourself or stream the raw compressed data.
267
268###### cache
269
270Type: `Object`<br>
271Default: `false`
272
273[Cache adapter instance](#cache-adapters) for storing cached data.
274
275###### request
276
277Type: `Function`<br>
278Default: `http.request` `https.request` *(depending on the protocol)*
279
280Custom request function. The main purpose of this is to [support HTTP2 using a wrapper](#experimental-http2-support).
281
282###### useElectronNet
283
284Type: `boolean`<br>
285Default: `false`
286
287When used in Electron, Got will use [`electron.net`](https://electronjs.org/docs/api/net/) instead of the Node.js `http` module. According to the Electron docs, it should be fully compatible, but it's not entirely. See [#443](https://github.com/sindresorhus/got/issues/443) and [#461](https://github.com/sindresorhus/got/issues/461).
288
289###### throwHttpErrors
290
291Type: `boolean`<br>
292Default: `true`
293
294Determines if a `got.HTTPError` is thrown for error responses (non-2xx status codes).
295
296If this is disabled, requests that encounter an error status code will be resolved with the `response` instead of throwing. This may be useful if you are checking for resource availability and are expecting error responses.
297
298###### agent
299
300Same as the [`agent` option](https://nodejs.org/api/http.html#http_http_request_url_options_callback) for `http.request`, but with an extra feature:
301
302If you require different agents for different protocols, you can pass a map of agents to the `agent` option. This is necessary because a request to one protocol might redirect to another. In such a scenario, Got will switch over to the right protocol agent for you.
303
304```js
305const got = require('got');
306const HttpAgent = require('agentkeepalive');
307const {HttpsAgent} = HttpAgent;
308
309got('sindresorhus.com', {
310 agent: {
311 http: new HttpAgent(),
312 https: new HttpsAgent()
313 }
314});
315```
316
317###### hooks
318
319Type: `Object<string, Function[]>`<br>
320Default: `{beforeRequest: []}`
321
322Hooks allow modifications during the request lifecycle. Hook functions may be async and are run serially.
323
324###### hooks.beforeRequest
325
326Type: `Function[]`<br>
327Default: `[]`
328
329Called with the normalized request options. Got will make no further changes to the request before it is sent. This is especially useful in conjunction with [`got.extend()`](#instances) and [`got.create()`](advanced-creation.md) when you want to create an API client that, for example, uses HMAC-signing.
330
331See the [AWS section](#aws) for an example.
332
333**Note**: Modifying the `body` is not recommended because the `content-length` header has already been computed and assigned.
334
335#### Response
336
337The response object will typically be a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage), however, if returned from the cache it will be a [response-like object](https://github.com/lukechilds/responselike) which behaves in the same way.
338
339##### body
340
341Type: `string` `Object` *(depending on `options.json`)*
342
343The result of the request.
344
345##### url
346
347Type: `string`
348
349The request URL or the final URL after redirects.
350
351##### requestUrl
352
353Type: `string`
354
355The original request URL.
356
357##### timings
358
359Type: `Object`
360
361The object contains the following properties:
362
363- `start` - Time when the request started.
364- `socket` - Time when a socket was assigned to the request.
365- `lookup` - Time when the DNS lookup finished.
366- `connect` - Time when the socket successfully connected.
367- `upload` - Time when the request finished uploading.
368- `response` - Time when the request fired the `response` event.
369- `end` - Time when the response fired the `end` event.
370- `error` - Time when the request fired the `error` event.
371- `phases`
372 - `wait` - `timings.socket - timings.start`
373 - `dns` - `timings.lookup - timings.socket`
374 - `tcp` - `timings.connect - timings.lookup`
375 - `request` - `timings.upload - timings.connect`
376 - `firstByte` - `timings.response - timings.upload`
377 - `download` - `timings.end - timings.response`
378 - `total` - `timings.end - timings.start` or `timings.error - timings.start`
379
380**Note**: The time is a `number` representing the milliseconds elapsed since the UNIX epoch.
381
382##### fromCache
383
384Type: `boolean`
385
386Whether the response was retrieved from the cache.
387
388##### redirectUrls
389
390Type: `Array`
391
392The redirect URLs.
393
394##### retryCount
395
396Type: `number`
397
398The number of times the request was retried.
399
400#### Streams
401
402**Note**: Progress events, redirect events and request/response events can also be used with promises.
403
404#### got.stream(url, [options])
405
406Sets `options.stream` to `true`.
407
408Returns a [duplex stream](https://nodejs.org/api/stream.html#stream_class_stream_duplex) with additional events:
409
410##### .on('request', request)
411
412`request` event to get the request object of the request.
413
414**Tip**: You can use `request` event to abort request:
415
416```js
417got.stream('github.com')
418 .on('request', request => setTimeout(() => request.abort(), 50));
419```
420
421##### .on('response', response)
422
423The `response` event to get the response object of the final request.
424
425##### .on('redirect', response, nextOptions)
426
427The `redirect` event to get the response object of a redirect. The second argument is options for the next request to the redirect location.
428
429##### .on('uploadProgress', progress)
430##### .on('downloadProgress', progress)
431
432Progress events for uploading (sending a request) and downloading (receiving a response). The `progress` argument is an object like:
433
434```js
435{
436 percent: 0.1,
437 transferred: 1024,
438 total: 10240
439}
440```
441
442If it's not possible to retrieve the body size (can happen when streaming), `total` will be `null`.
443
444```js
445(async () => {
446 const response = await got('sindresorhus.com')
447 .on('downloadProgress', progress => {
448 // Report download progress
449 })
450 .on('uploadProgress', progress => {
451 // Report upload progress
452 });
453
454 console.log(response);
455})();
456```
457
458##### .on('error', error, body, response)
459
460The `error` event emitted in case of a protocol error (like `ENOTFOUND` etc.) or status error (4xx or 5xx). The second argument is the body of the server response in case of status error. The third argument is a response object.
461
462#### got.get(url, [options])
463#### got.post(url, [options])
464#### got.put(url, [options])
465#### got.patch(url, [options])
466#### got.head(url, [options])
467#### got.delete(url, [options])
468
469Sets `options.method` to the method name and makes a request.
470
471### Instances
472
473#### got.extend([options])
474
475Configure a new `got` instance with default `options`. `options` are merged with the parent instance's `defaults.options` using [`got.mergeOptions`](#gotmergeoptionsparentoptions-newoptions).
476
477```js
478const client = got.extend({
479 baseUrl: 'https://example.com',
480 headers: {
481 'x-unicorn': 'rainbow'
482 }
483});
484
485client.get('/demo');
486
487/* HTTP Request =>
488 * GET /demo HTTP/1.1
489 * Host: example.com
490 * x-unicorn: rainbow
491 */
492```
493
494```js
495(async () => {
496 const client = got.extend({
497 baseUrl: 'httpbin.org',
498 headers: {
499 'x-foo': 'bar'
500 }
501 });
502 const {headers} = (await client.get('/headers', {json: true})).body;
503 //=> headers['x-foo'] === 'bar'
504
505 const jsonClient = client.extend({
506 json: true,
507 headers: {
508 'x-baz': 'qux'
509 }
510 });
511 const {headers: headers2} = (await jsonClient.get('/headers')).body;
512 //=> headers2['x-foo'] === 'bar'
513 //=> headers2['x-baz'] === 'qux'
514})();
515```
516
517*Need more control over the behavior of Got? Check out the [`got.create()`](advanced-creation.md).*
518
519#### got.mergeOptions(parentOptions, newOptions)
520
521Extends parent options. Avoid using [object spread](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#Spread_in_object_literals) as it doesn't work recursively:
522
523```js
524const a = {headers: {cat: 'meow', wolf: ['bark', 'wrrr']}};
525const b = {headers: {cow: 'moo', wolf: ['auuu']}};
526
527{...a, ...b} // => {headers: {cow: 'moo', wolf: ['auuu']}}
528got.mergeOptions(a, b) // => {headers: {cat: 'meow', cow: 'moo', wolf: ['auuu']}}
529```
530
531Options are deeply merged to a new object. The value of each key is determined as follows:
532
533- If the new property is set to `undefined`, it keeps the old one.
534- If the parent property is an instance of `URL` and the new value is a `string` or `URL`, a new URL instance is created: [`new URL(new, parent)`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL#Syntax).
535- If the new property is a plain `Object`:
536 - If the parent property is a plain `Object` too, both values are merged recursively into a new `Object`.
537 - Otherwise, only the new value is deeply cloned.
538- If the new property is an `Array`, it overwrites the old one with a deep clone of the new property.
539- Otherwise, the new value is assigned to the key.
540
541## Errors
542
543Each error contains (if available) `statusCode`, `statusMessage`, `host`, `hostname`, `method`, `path`, `protocol` and `url` properties to make debugging easier.
544
545In Promise mode, the `response` is attached to the error.
546
547#### got.CacheError
548
549When a cache method fails, for example, if the database goes down or there's a filesystem error.
550
551#### got.RequestError
552
553When a request fails. Contains a `code` property with error class code, like `ECONNREFUSED`.
554
555#### got.ReadError
556
557When reading from response stream fails.
558
559#### got.ParseError
560
561When `json` option is enabled, server response code is 2xx, and `JSON.parse` fails.
562
563#### got.HTTPError
564
565When the server response code is not 2xx. Includes `statusCode`, `statusMessage`, and `redirectUrls` properties.
566
567#### got.MaxRedirectsError
568
569When the server redirects you more than ten times. Includes a `redirectUrls` property, which is an array of the URLs Got was redirected to before giving up.
570
571#### got.UnsupportedProtocolError
572
573When given an unsupported protocol.
574
575#### got.CancelError
576
577When the request is aborted with `.cancel()`.
578
579#### got.TimeoutError
580
581When the request is aborted due to a [timeout](#timeout)
582
583## Aborting the request
584
585The promise returned by Got has a [`.cancel()`](https://github.com/sindresorhus/p-cancelable) method which when called, aborts the request.
586
587```js
588(async () => {
589 const request = got(url, options);
590
591 // …
592
593 // In another part of the code
594 if (something) {
595 request.cancel();
596 }
597
598 // …
599
600 try {
601 await request;
602 } catch (error) {
603 if (request.isCanceled) { // Or `error instanceof got.CancelError`
604 // Handle cancelation
605 }
606
607 // Handle other errors
608 }
609})();
610```
611
612<a name="cache-adapters"></a>
613## Cache
614
615Got implements [RFC 7234](http://httpwg.org/specs/rfc7234.html) compliant HTTP caching which works out of the box in-memory and is easily pluggable with a wide range of storage adapters. Fresh cache entries are served directly from the cache, and stale cache entries are revalidated with `If-None-Match`/`If-Modified-Since` headers. You can read more about the underlying cache behavior in the [`cacheable-request` documentation](https://github.com/lukechilds/cacheable-request).
616
617You can use the JavaScript `Map` type as an in-memory cache:
618
619```js
620const got = require('got');
621const map = new Map();
622
623(async () => {
624 let response = await got('sindresorhus.com', {cache: map});
625 console.log(response.fromCache);
626 //=> false
627
628 response = await got('sindresorhus.com', {cache: map});
629 console.log(response.fromCache);
630 //=> true
631})();
632```
633
634Got uses [Keyv](https://github.com/lukechilds/keyv) internally to support a wide range of storage adapters. For something more scalable you could use an [official Keyv storage adapter](https://github.com/lukechilds/keyv#official-storage-adapters):
635
636```
637$ npm install @keyv/redis
638```
639
640```js
641const got = require('got');
642const KeyvRedis = require('@keyv/redis');
643
644const redis = new KeyvRedis('redis://user:pass@localhost:6379');
645
646got('sindresorhus.com', {cache: redis});
647```
648
649Got supports anything that follows the Map API, so it's easy to write your own storage adapter or use a third-party solution.
650
651For example, the following are all valid storage adapters:
652
653```js
654const storageAdapter = new Map();
655// Or
656const storageAdapter = require('./my-storage-adapter');
657// Or
658const QuickLRU = require('quick-lru');
659const storageAdapter = new QuickLRU({maxSize: 1000});
660
661got('sindresorhus.com', {cache: storageAdapter});
662```
663
664View the [Keyv docs](https://github.com/lukechilds/keyv) for more information on how to use storage adapters.
665
666
667## Proxies
668
669You can use the [`tunnel`](https://github.com/koichik/node-tunnel) package with the `agent` option to work with proxies:
670
671```js
672const got = require('got');
673const tunnel = require('tunnel-agent');
674
675got('sindresorhus.com', {
676 agent: tunnel.httpOverHttp({
677 proxy: {
678 host: 'localhost'
679 }
680 })
681});
682```
683
684Check out [`global-tunnel`](https://github.com/np-maintain/global-tunnel) if you want to configure proxy support for all HTTP/HTTPS traffic in your app.
685
686
687## Cookies
688
689You can use the [`tough-cookie`](https://github.com/salesforce/tough-cookie) package:
690
691```js
692const got = require('got');
693const {CookieJar} = require('tough-cookie');
694
695const cookieJar = new CookieJar();
696cookieJar.setCookie('foo=bar', 'https://www.google.com');
697
698got('google.com', {cookieJar});
699```
700
701
702## Form data
703
704You can use the [`form-data`](https://github.com/form-data/form-data) package to create POST request with form data:
705
706```js
707const fs = require('fs');
708const got = require('got');
709const FormData = require('form-data');
710const form = new FormData();
711
712form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
713
714got.post('google.com', {
715 body: form
716});
717```
718
719
720## OAuth
721
722You can use the [`oauth-1.0a`](https://github.com/ddo/oauth-1.0a) package to create a signed OAuth request:
723
724```js
725const got = require('got');
726const crypto = require('crypto');
727const OAuth = require('oauth-1.0a');
728
729const oauth = OAuth({
730 consumer: {
731 key: process.env.CONSUMER_KEY,
732 secret: process.env.CONSUMER_SECRET
733 },
734 signature_method: 'HMAC-SHA1',
735 hash_function: (baseString, key) => crypto.createHmac('sha1', key).update(baseString).digest('base64')
736});
737
738const token = {
739 key: process.env.ACCESS_TOKEN,
740 secret: process.env.ACCESS_TOKEN_SECRET
741};
742
743const url = 'https://api.twitter.com/1.1/statuses/home_timeline.json';
744
745got(url, {
746 headers: oauth.toHeader(oauth.authorize({url, method: 'GET'}, token)),
747 json: true
748});
749```
750
751
752## Unix Domain Sockets
753
754Requests can also be sent via [unix domain sockets](http://serverfault.com/questions/124517/whats-the-difference-between-unix-socket-and-tcp-ip-socket). Use the following URL scheme: `PROTOCOL://unix:SOCKET:PATH`.
755
756- `PROTOCOL` - `http` or `https` *(optional)*
757- `SOCKET` - Absolute path to a unix domain socket, for example: `/var/run/docker.sock`
758- `PATH` - Request path, for example: `/v2/keys`
759
760```js
761got('http://unix:/var/run/docker.sock:/containers/json');
762
763// Or without protocol (HTTP by default)
764got('unix:/var/run/docker.sock:/containers/json');
765```
766
767
768## AWS
769
770Requests to AWS services need to have their headers signed. This can be accomplished by using the [`aws4`](https://www.npmjs.com/package/aws4) package. This is an example for querying an ["API Gateway"](https://docs.aws.amazon.com/apigateway/api-reference/signing-requests/) with a signed request.
771
772```js
773const AWS = require('aws-sdk');
774const aws4 = require('aws4');
775const got = require('got');
776
777const chain = new AWS.CredentialProviderChain();
778
779// Create a Got instance to use relative paths and signed requests
780const awsClient = got.extend({
781 baseUrl: 'https://<api-id>.execute-api.<api-region>.amazonaws.com/<stage>/',
782 hooks: {
783 beforeRequest: [
784 async options => {
785 const credentials = await chain.resolvePromise();
786 aws4.sign(options, credentials);
787 }
788 ]
789 }
790});
791
792const response = await awsClient('endpoint/path', {
793 // Request-specific options
794});
795```
796
797
798## Testing
799
800You can test your requests by using the [`nock`](https://github.com/node-nock/nock) package to mock an endpoint:
801
802```js
803const got = require('got');
804const nock = require('nock');
805
806nock('https://sindresorhus.com')
807 .get('/')
808 .reply(200, 'Hello world!');
809
810(async () => {
811 const response = await got('sindresorhus.com');
812 console.log(response.body);
813 //=> 'Hello world!'
814})();
815```
816
817If you need real integration tests you can use [`create-test-server`](https://github.com/lukechilds/create-test-server):
818
819```js
820const got = require('got');
821const createTestServer = require('create-test-server');
822
823(async () => {
824 const server = await createTestServer();
825 server.get('/', 'Hello world!');
826
827 const response = await got(server.url);
828 console.log(response.body);
829 //=> 'Hello world!'
830
831 await server.close();
832})();
833```
834
835
836## Tips
837
838### User Agent
839
840It's a good idea to set the `'user-agent'` header so the provider can more easily see how their resource is used. By default, it's the URL to this repo. You can omit this header by setting it to `null`.
841
842```js
843const got = require('got');
844const pkg = require('./package.json');
845
846got('sindresorhus.com', {
847 headers: {
848 'user-agent': `my-package/${pkg.version} (https://github.com/username/my-package)`
849 }
850});
851
852got('sindresorhus.com', {
853 headers: {
854 'user-agent': null
855 }
856});
857```
858
859### 304 Responses
860
861Bear in mind; if you send an `if-modified-since` header and receive a `304 Not Modified` response, the body will be empty. It's your responsibility to cache and retrieve the body contents.
862
863### Custom endpoints
864
865Use `got.extend()` to make it nicer to work with REST APIs. Especially if you use the `baseUrl` option.
866
867**Note:** Not to be confused with [`got.create()`](advanced-creation.md), which has no defaults.
868
869```js
870const got = require('got');
871const pkg = require('./package.json');
872
873const custom = got.extend({
874 baseUrl: 'example.com',
875 json: true,
876 headers: {
877 'user-agent': `my-package/${pkg.version} (https://github.com/username/my-package)`
878 }
879});
880
881// Use `custom` exactly how you use `got`
882(async () => {
883 const list = await custom('/v1/users/list');
884})();
885```
886
887*Need to merge some instances into a single one? Check out [`got.mergeInstances()`](advanced-creation.md#merging-instances).*
888
889### Experimental HTTP2 support
890
891Got provides an experimental support for HTTP2 using the [`http2-wrapper`](https://github.com/szmarczak/http2-wrapper) package:
892
893```js
894const got = require('got');
895const {request} = require('http2-wrapper');
896
897const h2got = got.extend({request});
898
899(async () => {
900 const {body} = await h2got('https://nghttp2.org/httpbin/headers');
901 console.log(body);
902})();
903```
904
905## Comparison
906
907| | `got` | `request` | `node-fetch` | `axios` |
908|-----------------------|:------------:|:------------:|:------------:|:------------:|
909| HTTP/2 support | ❔ | ✖ | ✖ | ✖ |
910| Browser support | ✖ | ✖ | ✔* | ✔ |
911| Electron support | ✔ | ✖ | ✖ | ✖ |
912| Promise API | ✔ | ✔ | ✔ | ✔ |
913| Stream API | ✔ | ✔ | ✖ | ✖ |
914| Request cancelation | ✔ | ✖ | ✖ | ✔ |
915| RFC compliant caching | ✔ | ✖ | ✖ | ✖ |
916| Cookies (out-of-box) | ✔ | ✔ | ✖ | ✖ |
917| Follows redirects | ✔ | ✔ | ✔ | ✔ |
918| Retries on failure | ✔ | ✖ | ✖ | ✖ |
919| Progress events | ✔ | ✖ | ✖ | Browser only |
920| Handles gzip/deflate | ✔ | ✔ | ✔ | ✔ |
921| Advanced timeouts | ✔ | ✖ | ✖ | ✖ |
922| Timings | ✔ | ✔ | ✖ | ✖ |
923| Errors with metadata | ✔ | ✖ | ✖ | ✔ |
924| JSON mode | ✔ | ✔ | ✖ | ✔ |
925| Custom defaults | ✔ | ✔ | ✖ | ✔ |
926| Composable | ✔ | ✖ | ✖ | ✖ |
927| Hooks | ✔ | ✖ | ✖ | ✔ |
928| Issues open | ![][gio] | ![][rio] | ![][nio] | ![][aio] |
929| Issues closed | ![][gic] | ![][ric] | ![][nic] | ![][aic] |
930| Downloads | ![][gd] | ![][rd] | ![][nd] | ![][ad] |
931| Coverage | ![][gc] | ![][rc] | ![][nc] | ![][ac] |
932| Build | ![][gb] | ![][rb] | ![][nb] | ![][ab] |
933| Bugs | ![][gbg] | ![][rbg] | ![][nbg] | ![][abg] |
934| Dependents | ![][gdp] | ![][rdp] | ![][ndp] | ![][adp] |
935| Install size | ![][gis] | ![][ris] | ![][nis] | ![][ais] |
936
937\* It's almost API compatible with the browser `fetch` API.<br>
938❔ Experimental support.
939
940<!-- ISSUES OPEN -->
941[gio]: https://img.shields.io/github/issues/sindresorhus/got.svg
942[rio]: https://img.shields.io/github/issues/request/request.svg
943[nio]: https://img.shields.io/github/issues/bitinn/node-fetch.svg
944[aio]: https://img.shields.io/github/issues/axios/axios.svg
945
946<!-- ISSUES CLOSED -->
947[gic]: https://img.shields.io/github/issues-closed/sindresorhus/got.svg
948[ric]: https://img.shields.io/github/issues-closed/request/request.svg
949[nic]: https://img.shields.io/github/issues-closed/bitinn/node-fetch.svg
950[aic]: https://img.shields.io/github/issues-closed/axios/axios.svg
951
952<!-- DOWNLOADS -->
953[gd]: https://img.shields.io/npm/dm/got.svg
954[rd]: https://img.shields.io/npm/dm/request.svg
955[nd]: https://img.shields.io/npm/dm/node-fetch.svg
956[ad]: https://img.shields.io/npm/dm/axios.svg
957
958<!-- COVERAGE -->
959[gc]: https://coveralls.io/repos/github/sindresorhus/got/badge.svg?branch=master
960[rc]: https://coveralls.io/repos/github/request/request/badge.svg?branch=master
961[nc]: https://coveralls.io/repos/github/bitinn/node-fetch/badge.svg?branch=master
962[ac]: https://coveralls.io/repos/github/mzabriskie/axios/badge.svg?branch=master
963
964<!-- BUILD -->
965[gb]: https://travis-ci.org/sindresorhus/got.svg?branch=master
966[rb]: https://travis-ci.org/request/request.svg?branch=master
967[nb]: https://travis-ci.org/bitinn/node-fetch.svg?branch=master
968[ab]: https://travis-ci.org/axios/axios.svg?branch=master
969
970<!-- BUGS -->
971[gbg]: https://badgen.net/github/label-issues/sindresorhus/got/bug/open
972[rbg]: https://badgen.net/github/label-issues/request/request/Needs%20investigation/open
973[nbg]: https://badgen.net/github/label-issues/bitinn/node-fetch/bug/open
974[abg]: https://badgen.net/github/label-issues/axios/axios/bug/open
975
976<!-- DEPENDENTS -->
977[gdp]: https://badgen.net/npm/dependents/got
978[rdp]: https://badgen.net/npm/dependents/request
979[ndp]: https://badgen.net/npm/dependents/node-fetch
980[adp]: https://badgen.net/npm/dependents/axios
981
982<!-- INSTALL SIZE -->
983[gis]: https://packagephobia.now.sh/badge?p=got
984[ris]: https://packagephobia.now.sh/badge?p=request
985[nis]: https://packagephobia.now.sh/badge?p=node-fetch
986[ais]: https://packagephobia.now.sh/badge?p=axios
987
988
989## Related
990
991- [gh-got](https://github.com/sindresorhus/gh-got) - Got convenience wrapper to interact with the GitHub API
992- [gl-got](https://github.com/singapore/gl-got) - Got convenience wrapper to interact with the GitLab API
993- [travis-got](https://github.com/samverschueren/travis-got) - Got convenience wrapper to interact with the Travis API
994- [graphql-got](https://github.com/kevva/graphql-got) - Got convenience wrapper to interact with GraphQL
995- [GotQL](https://github.com/khaosdoctor/gotql) - Got convenience wrapper to interact with GraphQL using JSON-parsed queries instead of strings
996
997
998## Maintainers
999
1000[![Sindre Sorhus](https://github.com/sindresorhus.png?size=100)](https://sindresorhus.com) | [![Vsevolod Strukchinsky](https://github.com/floatdrop.png?size=100)](https://github.com/floatdrop) | [![Alexander Tesfamichael](https://github.com/AlexTes.png?size=100)](https://github.com/AlexTes) | [![Luke Childs](https://github.com/lukechilds.png?size=100)](https://github.com/lukechilds) | [![Szymon Marczak](https://github.com/szmarczak.png?size=100)](https://github.com/szmarczak) | [![Brandon Smith](https://github.com/brandon93s.png?size=100)](https://github.com/brandon93s)
1001---|---|---|---|---|---
1002[Sindre Sorhus](https://sindresorhus.com) | [Vsevolod Strukchinsky](https://github.com/floatdrop) | [Alexander Tesfamichael](https://alextes.me) | [Luke Childs](https://github.com/lukechilds) | [Szymon Marczak](https://github.com/szmarczak) | [Brandon Smith](https://github.com/brandon93s)
1003
1004
1005## License
1006
1007MIT