3 <img width="360" src="https://rawgit.com/sindresorhus/got/master/media/logo.svg" alt="got">
9 > Simplified HTTP requests
11 [![Build Status](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)
13 A nicer interface to the built-in [`http`](http://nodejs.org/api/http.html) module.
15 It supports following redirects, promises, streams, retries, automagically handling gzip/deflate and some convenience options.
17 Created because [`request`](https://github.com/request/request) is bloated *(several megabytes!)*.
22 **WARNING: Node.js 4 or higher is required for got@6 and above.** For older Node.js versions use [got@5](https://github.com/sindresorhus/got/tree/v5.x).
25 $ npm install --save got
32 const fs = require('fs');
33 const got = require('got');
37 console.log(response.body);
38 //=> '<!doctype html> ...'
41 console.log(error.response.body);
42 //=> 'Internal server error ...'
46 got.stream('todomvc.com').pipe(fs.createWriteStream('index.html'));
48 // For POST, PUT and PATCH methods got.stream returns a WritableStream
49 fs.createReadStream('index.html').pipe(got.stream.post('todomvc.com'));
55 It's a `GET` request by default, but can be changed in `options`.
57 #### got(url, [options])
59 Returns a Promise for a `response` object with a `body` property, a `url` property with the request URL or the final URL after redirects, and a `requestUrl` property with the original request URL.
63 Type: `string`, `object`
65 The URL to request or a [`http.request` options](https://nodejs.org/api/http.html#http_http_request_options_callback) object.
67 Properties from `options` will override properties in the parsed `url`.
73 Any of the [`http.request`](http://nodejs.org/api/http.html#http_http_request_options_callback) options.
77 Type: `string`, `buffer`, `readableStream`, `object`
79 *This is mutually exclusive with stream mode.*
81 Body that will be sent with a `POST` request.
83 If present in `options` and `options.method` is not set, `options.method` will be set to `POST`.
85 If `content-length` or `transfer-encoding` is not set in `options.headers` and `body` is a string or buffer, `content-length` will be set to the body length.
87 If `body` is a plain object, it will be stringified with [`querystring.stringify`](https://nodejs.org/api/querystring.html#querystring_querystring_stringify_obj_sep_eq_options) and sent as `application/x-www-form-urlencoded`.
91 Type: `string`, `null`<br>
94 Encoding to be used on `setEncoding` of the response data. If `null`, the body is returned as a Buffer.
101 *This is mutually exclusive with stream mode.*
103 Parse response body with `JSON.parse` and set `accept` header to `application/json`.
107 Type: `string`, `object`<br>
109 Query string object that will be added to the request URL. This will override the query string in `url`.
113 Type: `number`, `object`
115 Milliseconds to wait for a server to send response headers before aborting request with `ETIMEDOUT` error.
117 Option accepts `object` with separate `connect` and `socket` fields for connection and socket inactivity timeouts.
121 Type: `number`, `function`<br>
124 Number of request retries when network errors happens. Delays between retries counts with function `1000 * Math.pow(2, retry) + Math.random() * 100`, where `retry` is attempt number (starts from 0).
126 Option accepts `function` with `retry` and `error` arguments. Function must return delay in milliseconds (`0` return value cancels retry).
128 **Note:** if `retries` is `number`, `ENOTFOUND` and `ENETUNREACH` error will not be retried (see full list in [`is-retry-allowed`](https://github.com/floatdrop/is-retry-allowed/blob/master/index.js#L12) module).
130 ###### followRedirect
135 Defines if redirect responses should be followed automatically.
140 #### got.stream(url, [options])
142 `stream` method will return Duplex stream with additional events:
144 ##### .on('request', request)
146 `request` event to get the request object of the request.
148 **Tip**: You can use `request` event to abort request:
151 got.stream('github.com')
152 .on('request', req => setTimeout(() => req.abort(), 50));
155 ##### .on('response', response)
157 `response` event to get the response object of the final request.
159 ##### .on('redirect', response, nextOptions)
161 `redirect` event to get the response object of a redirect. The second argument is options for the next request to the redirect location.
163 ##### .on('error', error, body, response)
165 `error` event emitted in case of 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 response object.
167 #### got.get(url, [options])
168 #### got.post(url, [options])
169 #### got.put(url, [options])
170 #### got.patch(url, [options])
171 #### got.head(url, [options])
172 #### got.delete(url, [options])
174 Sets `options.method` to the method name and makes a request.
179 Each error contains (if available) `statusCode`, `statusMessage`, `host`, `hostname`, `method` and `path` properties to make debugging easier.
181 In Promise mode, the `response` is attached to the error.
183 #### got.RequestError
185 When a request fails. Contains a `code` property with error class code, like `ECONNREFUSED`.
189 When reading from response stream fails.
193 When `json` option is enabled and `JSON.parse` fails.
197 When server response code is not 2xx. Contains `statusCode` and `statusMessage`.
199 #### got.MaxRedirectsError
201 When server redirects you more than 10 times.
206 You can use the [`tunnel`](https://github.com/koichik/node-tunnel) module with the `agent` option to work with proxies:
209 const got = require('got');
210 const tunnel = require('tunnel');
213 agent: tunnel.httpOverHttp({
224 You can use the [`cookie`](https://github.com/jshttp/cookie) module to include cookies in a request:
227 const got = require('got');
228 const cookie = require('cookie');
232 cookie: cookie.serialize('foo', 'bar')
240 You can use the [`form-data`](https://github.com/form-data/form-data) module to create POST request with form data:
243 const fs = require('fs');
244 const got = require('got');
245 const FormData = require('form-data');
246 const form = new FormData();
248 form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
250 got.post('google.com', {
258 You can use the [`oauth-1.0a`](https://github.com/ddo/oauth-1.0a) module to create a signed OAuth request:
261 const got = require('got');
262 const crypto = require('crypto');
263 const OAuth = require('oauth-1.0a');
265 const oauth = OAuth({
267 key: process.env.CONSUMER_KEY,
268 secret: process.env.CONSUMER_SECRET
270 signature_method: 'HMAC-SHA1',
271 hash_function: (baseString, key) => crypto.createHmac('sha1', key).update(baseString).digest('base64')
275 key: process.env.ACCESS_TOKEN,
276 secret: process.env.ACCESS_TOKEN_SECRET
279 const url = 'https://api.twitter.com/1.1/statuses/home_timeline.json';
282 headers: oauth.toHeader(oauth.authorize({url, method: 'GET'}, token)),
288 ## Unix Domain Sockets
290 Requests 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`.
292 - `PROTOCOL` - `http` or `https` *(optional)*
293 - `SOCKET` - absolute path to a unix domain socket, e.g. `/var/run/docker.sock`
294 - `PATH` - request path, e.g. `/v2/keys`
297 got('http://unix:/var/run/docker.sock:/containers/json');
299 // or without protocol (http by default)
300 got('unix:/var/run/docker.sock:/containers/json');
306 It'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.
309 const got = require('got');
310 const pkg = require('./package.json');
314 'user-agent': `my-module/${pkg.version} (https://github.com/username/my-module)`
322 - [gh-got](https://github.com/sindresorhus/gh-got) - Convenience wrapper for interacting with the GitHub API
323 - [travis-got](https://github.com/samverschueren/travis-got) - Convenience wrapper for interacting with the Travis API
328 [![Sindre Sorhus](https://avatars.githubusercontent.com/u/170270?v=3&s=100)](https://sindresorhus.com) | [![Vsevolod Strukchinsky](https://avatars.githubusercontent.com/u/365089?v=3&s=100)](https://github.com/floatdrop)
330 [Sindre Sorhus](https://sindresorhus.com) | [Vsevolod Strukchinsky](https://github.com/floatdrop)
335 MIT © [Sindre Sorhus](https://sindresorhus.com)