or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-ky

Tiny and elegant HTTP client based on the Fetch API

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/ky@1.10.x

To install, run

npx @tessl/cli install tessl/npm-ky@1.10.0

0

# Ky

1

2

Ky is a tiny and elegant HTTP client based on the Fetch API. It provides a simplified interface for making HTTP requests with modern features like automatic retries, JSON handling, timeout support, URL prefixing, and an extensible hooks system. Ky works seamlessly across browsers, Node.js, Bun, and Deno environments.

3

4

## Package Information

5

6

- **Package Name**: ky

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install ky`

10

11

## Core Imports

12

13

```typescript

14

import ky from "ky";

15

```

16

17

For CommonJS:

18

19

```javascript

20

const ky = require("ky").default;

21

```

22

23

## Basic Usage

24

25

```typescript

26

import ky from "ky";

27

28

// Simple GET request

29

const user = await ky.get("https://api.example.com/user/123").json();

30

31

// POST with JSON data

32

const response = await ky.post("https://api.example.com/users", {

33

json: { name: "Alice", email: "alice@example.com" }

34

}).json();

35

36

// Request with options

37

const data = await ky("https://api.example.com/data", {

38

timeout: 5000,

39

retry: 3,

40

headers: { "Authorization": "Bearer token" }

41

}).json();

42

```

43

44

## Architecture

45

46

Ky is built around several key components:

47

48

- **Instance System**: Default ky instance with the ability to create custom instances with different defaults

49

- **HTTP Methods**: Convenient shortcuts for common HTTP methods (get, post, put, patch, delete, head)

50

- **Response Promise**: Enhanced promises with body method shortcuts (json, text, blob, etc.)

51

- **Options System**: Comprehensive configuration supporting both Fetch API options and Ky-specific extensions

52

- **Retry Engine**: Intelligent retry logic with configurable backoff strategies and status code handling

53

- **Hooks System**: Extensible request/response lifecycle hooks for custom behavior

54

- **Error Handling**: Automatic HTTP error throwing with detailed error information

55

56

## Capabilities

57

58

### HTTP Methods

59

60

Core HTTP request methods with convenient shortcuts and full TypeScript support.

61

62

```typescript { .api }

63

// Main request function

64

function ky<T>(url: Input, options?: Options): ResponsePromise<T>;

65

66

// HTTP method shortcuts

67

function get<T>(url: Input, options?: Options): ResponsePromise<T>;

68

function post<T>(url: Input, options?: Options): ResponsePromise<T>;

69

function put<T>(url: Input, options?: Options): ResponsePromise<T>;

70

function patch<T>(url: Input, options?: Options): ResponsePromise<T>;

71

function delete<T>(url: Input, options?: Options): ResponsePromise<T>;

72

function head(url: Input, options?: Options): ResponsePromise;

73

```

74

75

[HTTP Methods](./http-methods.md)

76

77

### Instance Management

78

79

Create and extend ky instances with custom defaults for different API endpoints or configurations.

80

81

```typescript { .api }

82

function create(defaultOptions?: Options): KyInstance;

83

function extend(defaultOptions?: Options | ((parentOptions: Options) => Options)): KyInstance;

84

```

85

86

[Instance Management](./instances.md)

87

88

### Configuration Options

89

90

Comprehensive options for customizing request behavior including JSON handling, retries, timeouts, and progress tracking.

91

92

```typescript { .api }

93

interface Options extends KyOptions, Omit<RequestInit, 'headers'> {

94

method?: LiteralUnion<HttpMethod, string>;

95

headers?: KyHeadersInit;

96

}

97

98

interface KyOptions {

99

json?: unknown;

100

parseJson?: (text: string) => unknown;

101

stringifyJson?: (data: unknown) => string;

102

searchParams?: SearchParamsOption;

103

prefixUrl?: URL | string;

104

retry?: RetryOptions | number;

105

timeout?: number | false;

106

throwHttpErrors?: boolean;

107

onDownloadProgress?: (progress: Progress, chunk: Uint8Array) => void;

108

onUploadProgress?: (progress: Progress, chunk: Uint8Array) => void;

109

fetch?: (input: Input, init?: RequestInit) => Promise<Response>;

110

hooks?: Hooks;

111

}

112

```

113

114

[Configuration](./configuration.md)

115

116

### Response Handling

117

118

Enhanced response promises with body method shortcuts and automatic error handling for non-2xx status codes.

119

120

```typescript { .api }

121

interface ResponsePromise<T = unknown> extends Promise<KyResponse<T>> {

122

arrayBuffer(): Promise<ArrayBuffer>;

123

blob(): Promise<Blob>;

124

formData(): Promise<FormData>;

125

bytes(): Promise<Uint8Array>;

126

json<J = T>(): Promise<J>;

127

text(): Promise<string>;

128

}

129

```

130

131

[Response Handling](./responses.md)

132

133

### Retry System

134

135

Configurable retry logic with exponential backoff, status code filtering, and Retry-After header support.

136

137

```typescript { .api }

138

interface RetryOptions {

139

limit?: number;

140

methods?: string[];

141

statusCodes?: number[];

142

afterStatusCodes?: number[];

143

maxRetryAfter?: number;

144

backoffLimit?: number;

145

delay?: (attemptCount: number) => number;

146

}

147

```

148

149

[Retry System](./retry.md)

150

151

### Hooks System

152

153

Extensible lifecycle hooks for request modification, response processing, error handling, and retry customization.

154

155

```typescript { .api }

156

interface Hooks {

157

beforeRequest?: BeforeRequestHook[];

158

beforeRetry?: BeforeRetryHook[];

159

afterResponse?: AfterResponseHook[];

160

beforeError?: BeforeErrorHook[];

161

}

162

```

163

164

[Hooks System](./hooks.md)

165

166

### Error Handling

167

168

Comprehensive error handling with detailed HTTP and timeout error classes containing request and response information.

169

170

```typescript { .api }

171

class HTTPError<T = unknown> extends Error {

172

response: KyResponse<T>;

173

request: KyRequest;

174

options: NormalizedOptions;

175

}

176

177

class TimeoutError extends Error {

178

request: KyRequest;

179

}

180

```

181

182

[Error Handling](./errors.md)

183

184

## Types

185

186

Core type definitions used throughout the Ky API:

187

188

```typescript { .api }

189

interface NormalizedOptions extends RequestInit {

190

method: NonNullable<RequestInit['method']>;

191

credentials?: NonNullable<RequestInit['credentials']>;

192

retry: RetryOptions;

193

prefixUrl: string;

194

onDownloadProgress: Options['onDownloadProgress'];

195

onUploadProgress: Options['onUploadProgress'];

196

}

197

type Input = string | URL | Request;

198

199

type KyInstance = {

200

<T>(url: Input, options?: Options): ResponsePromise<T>;

201

get: <T>(url: Input, options?: Options) => ResponsePromise<T>;

202

post: <T>(url: Input, options?: Options) => ResponsePromise<T>;

203

put: <T>(url: Input, options?: Options) => ResponsePromise<T>;

204

patch: <T>(url: Input, options?: Options) => ResponsePromise<T>;

205

delete: <T>(url: Input, options?: Options) => ResponsePromise<T>;

206

head: (url: Input, options?: Options) => ResponsePromise;

207

create: (defaultOptions?: Options) => KyInstance;

208

extend: (defaultOptions?: Options | ((parentOptions: Options) => Options)) => KyInstance;

209

readonly stop: typeof stop;

210

};

211

212

interface KyRequest<T = unknown> extends Request {

213

json: <J = T>() => Promise<J>;

214

}

215

216

interface KyResponse<T = unknown> extends Response {

217

json: <J = T>() => Promise<J>;

218

}

219

220

interface Progress {

221

percent: number;

222

transferredBytes: number;

223

totalBytes: number;

224

}

225

226

type SearchParamsInit = string | string[][] | Record<string, string> | URLSearchParams | undefined;

227

228

type SearchParamsOption = SearchParamsInit | Record<string, string | number | boolean | undefined> | Array<Array<string | number | boolean>>;

229

230

type KyHeadersInit = NonNullable<RequestInit['headers']> | Record<string, string | undefined>;

231

232

type LiteralUnion<LiteralType, BaseType extends string> = LiteralType | (BaseType & Record<never, never>);

233

234

type HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete';

235

236

type BeforeRequestHook = (

237

request: KyRequest,

238

options: NormalizedOptions

239

) => Request | Response | void | Promise<Request | Response | void>;

240

241

type BeforeRetryState = {

242

request: KyRequest;

243

options: NormalizedOptions;

244

error: Error;

245

retryCount: number;

246

};

247

248

type BeforeRetryHook = (options: BeforeRetryState) => typeof stop | void | Promise<typeof stop | void>;

249

250

type AfterResponseHook = (

251

request: KyRequest,

252

options: NormalizedOptions,

253

response: KyResponse

254

) => Response | void | Promise<Response | void>;

255

256

type BeforeErrorHook = (error: HTTPError) => HTTPError | Promise<HTTPError>;

257

258

declare const stop: unique symbol;

259

```