or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.mdinterceptors.mdmime-system.mdurl-building.md

index.mddocs/

0

# rest.js

1

2

rest.js is a RESTful HTTP client library designed for both Node.js and browser environments. It provides a composable architecture where the core client functionality can be extended through interceptors that wrap request and response handling, allowing developers to add features like authentication, error handling, MIME type conversion, and more.

3

4

## Package Information

5

6

- **Package Name**: rest

7

- **Package Type**: npm

8

- **Language**: JavaScript

9

- **Installation**: `npm install rest`

10

11

## Core Imports

12

13

```javascript

14

const rest = require('rest');

15

```

16

17

For ES modules:

18

19

```javascript

20

import rest from 'rest';

21

```

22

23

Browser-specific client:

24

25

```javascript

26

const rest = require('rest/browser');

27

```

28

29

Node.js-specific client:

30

31

```javascript

32

const rest = require('rest/node');

33

```

34

35

## Basic Usage

36

37

```javascript

38

const rest = require('rest');

39

40

// Simple GET request

41

rest('/api/users').then(function(response) {

42

console.log('Status:', response.status.code);

43

console.log('Data:', response.entity);

44

});

45

46

// POST request with data

47

rest({

48

path: '/api/users',

49

method: 'POST',

50

entity: { name: 'John', email: 'john@example.com' },

51

headers: { 'Content-Type': 'application/json' }

52

}).then(function(response) {

53

console.log('Created user:', response.entity);

54

});

55

```

56

57

## Architecture

58

59

rest.js is built around several key components:

60

61

- **Default Client**: Core HTTP client that can be configured for different platforms (Node.js, browsers)

62

- **Interceptor System**: Composable middleware pattern for extending client functionality

63

- **MIME System**: Automatic content type conversion with pluggable converters

64

- **URL Building**: Powerful URL construction with template support

65

- **Promise-based**: All operations return promises with additional HTTP-specific helper methods

66

67

## Capabilities

68

69

### Basic HTTP Client

70

71

Core client functionality for making HTTP requests with configurable defaults and platform-specific implementations.

72

73

```javascript { .api }

74

/**

75

* Make an HTTP request

76

* @param {string|Request} request - URL string or request object

77

* @returns {ResponsePromise<Response>} Promise that resolves to HTTP response

78

*/

79

function rest(request)

80

81

interface Request {

82

method?: string; // HTTP method (default: 'GET')

83

path?: string; // URL path template

84

params?: object; // URL parameters and query string

85

headers?: object; // HTTP headers

86

entity?: any; // Request body

87

canceled?: boolean; // Cancellation flag

88

cancel?: function; // Cancellation function

89

originator?: Client; // Originating client reference

90

}

91

92

interface Response {

93

request: Request; // Original request object

94

raw: any; // Platform-specific response object

95

status: { // HTTP status information

96

code: number; // Status code (200, 404, etc.)

97

text: string; // Status text

98

};

99

headers: object; // Response headers

100

entity: any; // Response body

101

}

102

```

103

104

### Client Wrapping and Composition

105

106

Build custom clients by wrapping with interceptors for authentication, error handling, content negotiation, and more.

107

108

```javascript { .api }

109

/**

110

* Wrap a client with an interceptor

111

* @param {Interceptor} interceptor - Interceptor function

112

* @param {object} [config] - Configuration for the interceptor

113

* @returns {Client} New wrapped client

114

*/

115

client.wrap(interceptor, config)

116

117

/**

118

* Access the underlying client (when wrapped)

119

* @returns {Client} Target client

120

*/

121

client.skip()

122

```

123

124

[Interceptors](./interceptors.md)

125

126

### MIME Type Conversion

127

128

Automatic serialization and deserialization of request/response entities based on Content-Type headers, with support for JSON, form data, and custom converters.

129

130

```javascript { .api }

131

const mime = require('rest/interceptor/mime');

132

133

const client = rest.wrap(mime);

134

```

135

136

[MIME System](./mime-system.md)

137

138

### URL Building and Templates

139

140

Powerful URL construction with parameter substitution, query string building, and template support.

141

142

```javascript { .api }

143

const UrlBuilder = require('rest/UrlBuilder');

144

145

/**

146

* Create a URL builder

147

* @param {string} template - URL template

148

* @param {object} [params] - Default parameters

149

* @returns {UrlBuilder} URL builder instance

150

*/

151

function UrlBuilder(template, params)

152

```

153

154

[URL Building](./url-building.md)

155

156

## Response Promise Extensions

157

158

All client requests return enhanced promises with HTTP-specific helper methods:

159

160

```javascript { .api }

161

interface ResponsePromise<T> extends Promise<T> {

162

/** Get response status code */

163

status(): Promise<number>;

164

/** Get all response headers */

165

headers(): Promise<object>;

166

/** Get specific response header */

167

header(name: string): Promise<string>;

168

/** Get response entity/body */

169

entity(): Promise<any>;

170

/** Follow hypermedia relationships */

171

follow(rels: string | object | Array): ResponsePromise<Response>;

172

}

173

```

174

175

**Usage Examples:**

176

177

```javascript

178

rest('/api/user/123')

179

.status().then(function(code) {

180

console.log('Status code:', code);

181

});

182

183

rest('/api/user/123')

184

.entity().then(function(user) {

185

console.log('User data:', user);

186

});

187

188

rest('/api/user/123')

189

.header('content-type').then(function(type) {

190

console.log('Content type:', type);

191

});

192

```

193

194

## Configuration

195

196

```javascript

197

// Set default client

198

rest.setDefaultClient(customClient);

199

200

// Get current default client

201

const currentClient = rest.getDefaultClient();

202

203

// Reset to platform default

204

rest.resetDefaultClient();

205

```

206

207

## Wire.js Integration

208

209

rest.js provides first-class support for declarative configuration using wire.js dependency injection.

210

211

```javascript { .api }

212

const wirePlugin = require('rest/wire');

213

214

/**

215

* Wire.js plugin for rest client factory

216

* Provides 'rest' factory for declarative client composition

217

*/

218

```

219

220

**Usage Example:**

221

222

```javascript

223

// wire.js spec

224

{

225

client: {

226

rest: [

227

{ module: 'rest/interceptor/mime' },

228

{ module: 'rest/interceptor/errorCode', config: { code: 500 } }

229

]

230

},

231

$plugins: [{ module: 'rest/wire' }]

232

}

233

234

// Alternative syntax with parent client

235

{

236

apiClient: {

237

rest: {

238

parent: { $ref: 'customClient' },

239

interceptors: [

240

{ module: 'rest/interceptor/pathPrefix', config: { prefix: '/api/v1' } },

241

{ module: 'rest/interceptor/mime' }

242

]

243

}

244

},

245

$plugins: [{ module: 'rest/wire' }]

246

}

247

```