or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

client-construction.mdexecution.mdhelpers.mdhttp-client.mdindex.mdrequest-building.mdresolution.md

http-client.mddocs/

0

# HTTP Client and Request Handling

1

2

Customizable HTTP client with request/response serialization, interceptors, and platform-specific implementations.

3

4

## Capabilities

5

6

### HTTP Function

7

8

Core HTTP client for making requests with automatic serialization and error handling.

9

10

```javascript { .api }

11

/**

12

* Make HTTP request with automatic serialization

13

* @param url - Request URL or request object

14

* @param request - Request options (if url is string)

15

* @returns Promise resolving to response object

16

*/

17

function http(url: string | RequestObject, request?: HttpOptions): Promise<ResponseObject>;

18

19

interface HttpOptions {

20

/** HTTP method */

21

method?: string;

22

/** Request headers */

23

headers?: Record<string, string>;

24

/** Request body */

25

body?: any;

26

/** Request credentials policy */

27

credentials?: RequestCredentials;

28

/** Query parameters object */

29

query?: Record<string, any>;

30

/** Function to intercept and modify request */

31

requestInterceptor?: RequestInterceptor;

32

/** Function to intercept and modify response */

33

responseInterceptor?: ResponseInterceptor;

34

/** Custom fetch implementation */

35

userFetch?: FetchFunction;

36

/** AbortSignal for request cancellation */

37

signal?: AbortSignal;

38

}

39

40

interface ResponseObject {

41

/** Request URL */

42

url: string;

43

/** HTTP method used */

44

method: string;

45

/** HTTP status code */

46

status: number;

47

/** HTTP status text */

48

statusText: string;

49

/** Response headers as object */

50

headers: Record<string, string>;

51

/** Response body as text */

52

text: string;

53

/** Parsed response body */

54

body: any;

55

/** Alias for body */

56

obj: any;

57

/** Whether response was successful (2xx status) */

58

ok: boolean;

59

/** Alias for body */

60

data: any;

61

}

62

```

63

64

**Usage Examples:**

65

66

```javascript

67

import http from "swagger-client/http";

68

69

// Simple GET request

70

const response = await http("https://api.example.com/users");

71

console.log(response.body);

72

73

// POST request with JSON body

74

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

75

method: "POST",

76

headers: {

77

"Content-Type": "application/json"

78

},

79

body: {

80

name: "John Doe",

81

email: "john@example.com"

82

}

83

});

84

85

// Request with query parameters

86

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

87

query: {

88

page: 1,

89

limit: 10,

90

sort: "name"

91

}

92

});

93

94

// Request with custom headers

95

const response = await http("https://api.example.com/protected", {

96

headers: {

97

"Authorization": "Bearer token",

98

"X-API-Key": "api-key"

99

}

100

});

101

102

// Request object format

103

const response = await http({

104

url: "https://api.example.com/users",

105

method: "POST",

106

headers: { "Content-Type": "application/json" },

107

body: { name: "Jane Doe" }

108

});

109

```

110

111

### HTTP Client Factory

112

113

Create custom HTTP clients with pre-configured interceptors.

114

115

```javascript { .api }

116

/**

117

* Create custom HTTP client with interceptors

118

* @param httpFn - Base HTTP function

119

* @param preFetch - Function to modify request before sending

120

* @param postFetch - Function to modify response after receiving

121

* @returns Configured HTTP client function

122

*/

123

function makeHttp(

124

httpFn: HttpFunction,

125

preFetch?: PreFetchFunction,

126

postFetch?: PostFetchFunction

127

): HttpFunction;

128

129

interface PreFetchFunction {

130

(request: RequestObject): RequestObject | Promise<RequestObject>;

131

}

132

133

interface PostFetchFunction {

134

(response: ResponseObject): ResponseObject | Promise<ResponseObject>;

135

}

136

137

interface HttpFunction {

138

(url: string | RequestObject, options?: HttpOptions): Promise<ResponseObject>;

139

}

140

```

141

142

**Factory Examples:**

143

144

```javascript

145

import { makeHttp, http } from "swagger-client";

146

147

// Create HTTP client with authentication

148

const authenticatedHttp = makeHttp(

149

http,

150

(req) => {

151

req.headers = req.headers || {};

152

req.headers.Authorization = "Bearer " + getAccessToken();

153

return req;

154

}

155

);

156

157

// Create HTTP client with logging

158

const loggingHttp = makeHttp(

159

http,

160

(req) => {

161

console.log("→", req.method, req.url);

162

return req;

163

},

164

(res) => {

165

console.log("←", res.status, res.url);

166

return res;

167

}

168

);

169

170

// Create HTTP client with retry logic

171

const retryHttp = makeHttp(

172

http,

173

null, // no pre-fetch modification

174

async (res) => {

175

if (res.status >= 500 && res.retryCount < 3) {

176

res.retryCount = (res.retryCount || 0) + 1;

177

await new Promise(resolve => setTimeout(resolve, 1000));

178

return http(res.url, { ...res.originalRequest });

179

}

180

return res;

181

}

182

);

183

184

// Use custom HTTP client

185

const response = await authenticatedHttp("https://api.example.com/protected");

186

```

187

188

### Request Serialization

189

190

Automatic serialization of request data including query parameters and form data.

191

192

```javascript { .api }

193

/**

194

* Serialize request object

195

* @param request - Request object to serialize

196

* @returns Serialized request object

197

*/

198

function serializeRequest(request: RequestObject): RequestObject;

199

200

interface RequestObject {

201

url: string;

202

method: string;

203

headers: Record<string, string>;

204

body?: any;

205

query?: Record<string, any>;

206

credentials?: RequestCredentials;

207

requestInterceptor?: RequestInterceptor;

208

responseInterceptor?: ResponseInterceptor;

209

userFetch?: FetchFunction;

210

}

211

```

212

213

**Serialization Examples:**

214

215

```javascript

216

// Query parameter serialization

217

const request = {

218

url: "https://api.example.com/search",

219

query: {

220

q: "javascript",

221

page: 1,

222

filters: ["recent", "popular"]

223

}

224

};

225

// Results in: https://api.example.com/search?q=javascript&page=1&filters=recent&filters=popular

226

227

// Form data serialization

228

const request = {

229

url: "https://api.example.com/upload",

230

method: "POST",

231

headers: {

232

"Content-Type": "multipart/form-data"

233

},

234

body: {

235

file: fileObject,

236

description: "My file"

237

}

238

};

239

// Automatically creates FormData object

240

241

// JSON body serialization

242

const request = {

243

url: "https://api.example.com/users",

244

method: "POST",

245

body: {

246

name: "John",

247

email: "john@example.com"

248

}

249

};

250

// Body is automatically JSON.stringify'd when content-type is application/json

251

```

252

253

### Response Serialization

254

255

Automatic response parsing and header processing.

256

257

```javascript { .api }

258

/**

259

* Serialize response object

260

* @param response - Raw fetch Response

261

* @param url - Request URL

262

* @param request - Original request object

263

* @returns Serialized response object

264

*/

265

function serializeResponse(response: Response, url: string, request: RequestObject): Promise<ResponseObject>;

266

267

/**

268

* Serialize response headers

269

* @param headers - Headers object or Headers instance

270

* @returns Headers as plain object

271

*/

272

function serializeHeaders(headers: Headers | Record<string, string>): Record<string, string>;

273

274

/**

275

* Determine if response should be downloaded as text

276

* @param contentType - Response content type

277

* @returns Whether to download as text

278

*/

279

function shouldDownloadAsText(contentType: string): boolean;

280

```

281

282

**Response Processing Examples:**

283

284

```javascript

285

// Automatic JSON parsing

286

const response = await http("https://api.example.com/users.json");

287

console.log(response.body); // Parsed JSON object

288

console.log(response.text); // Raw JSON string

289

290

// Text response handling

291

const response = await http("https://api.example.com/readme.txt");

292

console.log(response.text); // Raw text content

293

console.log(response.body); // Same as text for non-JSON responses

294

295

// Binary response handling

296

const response = await http("https://api.example.com/image.png");

297

console.log(response.body); // ArrayBuffer or Blob depending on environment

298

299

// Header access

300

const response = await http("https://api.example.com/data");

301

console.log(response.headers["content-type"]);

302

console.log(response.headers["x-rate-limit"]);

303

```

304

305

### File Handling

306

307

Support for file uploads and multipart form data.

308

309

```javascript { .api }

310

/**

311

* Check if value is a file object

312

* @param value - Value to check

313

* @returns Whether value is a file

314

*/

315

function isFile(value: any): boolean;

316

317

/**

318

* Check if value is an array of files

319

* @param value - Value to check

320

* @returns Whether value is array of files

321

*/

322

function isArrayOfFile(value: any): boolean;

323

324

/**

325

* File wrapper with additional metadata

326

*/

327

class FileWithData {

328

constructor(data: any, file: File);

329

data: any;

330

file: File;

331

}

332

```

333

334

**File Examples:**

335

336

```javascript

337

// File upload

338

const fileInput = document.getElementById('file');

339

const file = fileInput.files[0];

340

341

const response = await http("https://api.example.com/upload", {

342

method: "POST",

343

body: {

344

file: file,

345

description: "Profile picture"

346

}

347

});

348

349

// Multiple file upload

350

const response = await http("https://api.example.com/upload-multiple", {

351

method: "POST",

352

body: {

353

files: [file1, file2, file3],

354

category: "documents"

355

}

356

});

357

358

// File with metadata

359

const fileWithData = new FileWithData({ id: 123 }, file);

360

const response = await http("https://api.example.com/upload", {

361

method: "POST",

362

body: {

363

fileData: fileWithData

364

}

365

});

366

```

367

368

### Request/Response Interceptors

369

370

Modify requests and responses during processing.

371

372

```javascript { .api }

373

interface RequestInterceptor {

374

(request: RequestObject): RequestObject | Promise<RequestObject>;

375

}

376

377

interface ResponseInterceptor {

378

(response: ResponseObject): ResponseObject | Promise<ResponseObject>;

379

}

380

```

381

382

**Interceptor Examples:**

383

384

```javascript

385

// Request interceptor for authentication

386

const authInterceptor = (req) => {

387

req.headers = req.headers || {};

388

req.headers.Authorization = `Bearer ${getToken()}`;

389

return req;

390

};

391

392

// Response interceptor for error handling

393

const errorInterceptor = (res) => {

394

if (res.status === 401) {

395

// Handle authentication error

396

redirectToLogin();

397

}

398

return res;

399

};

400

401

// Using interceptors

402

const response = await http("https://api.example.com/protected", {

403

requestInterceptor: authInterceptor,

404

responseInterceptor: errorInterceptor

405

});

406

407

// Async interceptors

408

const asyncInterceptor = async (req) => {

409

const token = await getTokenAsync();

410

req.headers.Authorization = `Bearer ${token}`;

411

return req;

412

};

413

```

414

415

### Platform-Specific Features

416

417

Features that work differently in browser vs Node.js environments.

418

419

```javascript { .api }

420

// Browser-specific: Works with native fetch, XMLHttpRequest fallback

421

// Node.js-specific: Works with node-fetch or native fetch (Node 18+)

422

423

// Credential handling

424

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

425

credentials: "include" // Browser: sends cookies, Node.js: no effect

426

});

427

428

// Custom fetch implementation

429

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

430

userFetch: customFetchImplementation

431

});

432

433

// Request cancellation

434

const controller = new AbortController();

435

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

436

signal: controller.signal

437

});

438

439

// Cancel the request

440

setTimeout(() => controller.abort(), 5000);

441

```

442

443

## Common Types

444

445

```javascript { .api }

446

interface RequestInterceptor {

447

(request: RequestObject): RequestObject | Promise<RequestObject>;

448

}

449

450

interface ResponseInterceptor {

451

(response: ResponseObject): ResponseObject | Promise<ResponseObject>;

452

}

453

454

interface FetchFunction {

455

(url: string, options?: RequestInit): Promise<Response>;

456

}

457

458

interface RequestCredentials {

459

"include" | "omit" | "same-origin";

460

}

461

462

interface RequestObject {

463

url: string;

464

method: string;

465

headers: Record<string, string>;

466

body?: any;

467

credentials?: RequestCredentials;

468

signal?: AbortSignal;

469

query?: Record<string, any>;

470

requestInterceptor?: RequestInterceptor;

471

responseInterceptor?: ResponseInterceptor;

472

userFetch?: FetchFunction;

473

}

474

475

interface ResponseObject {

476

url: string;

477

method: string;

478

status: number;

479

statusText: string;

480

headers: Record<string, string>;

481

text: string;

482

body: any;

483

obj: any;

484

ok: boolean;

485

data: any;

486

}

487

```