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

request-building.mddocs/

0

# Request Building and Parameters

1

2

Build HTTP requests from OpenAPI operations and parameters with version-specific handling for different spec formats.

3

4

## Capabilities

5

6

### Build Request Function

7

8

Build HTTP request objects from OpenAPI operation parameters.

9

10

```javascript { .api }

11

/**

12

* Build HTTP request from OpenAPI operation

13

* @param options - Request building options

14

* @returns HTTP request object ready for execution

15

*/

16

function buildRequest(options: BuildRequestOptions): RequestObject;

17

18

interface BuildRequestOptions {

19

/** OpenAPI specification object */

20

spec: object;

21

/** Operation ID to build request for */

22

operationId: string;

23

/** Parameter values for the operation */

24

parameters?: ParameterValues;

25

/** Security requirements and credentials */

26

securities?: SecurityRequirements;

27

/** Base URL override */

28

baseURL?: string;

29

/** Context URL for relative URL resolution */

30

contextUrl?: string;

31

/** Server URL override (OpenAPI 3.x) */

32

server?: string;

33

/** Server variable values (OpenAPI 3.x) */

34

serverVariables?: Record<string, string>;

35

/** Custom HTTP client */

36

http?: HttpClient;

37

/** Function to intercept requests */

38

requestInterceptor?: RequestInterceptor;

39

/** Function to intercept responses */

40

responseInterceptor?: ResponseInterceptor;

41

/** Custom fetch implementation */

42

userFetch?: FetchFunction;

43

/** AbortSignal for request cancellation */

44

signal?: AbortSignal;

45

/** URL scheme override (Swagger 2.0) */

46

scheme?: string;

47

/** Response content type preference */

48

responseContentType?: string;

49

/** Custom parameter builders */

50

parameterBuilders?: ParameterBuilders;

51

/** Server variable encoder function */

52

serverVariableEncoder?: (value: string) => string;

53

}

54

55

interface RequestObject {

56

/** Request URL with parameters applied */

57

url: string;

58

/** HTTP method */

59

method: string;

60

/** Request headers */

61

headers: Record<string, string>;

62

/** Request body */

63

body?: any;

64

/** Request credentials policy */

65

credentials: RequestCredentials;

66

/** AbortSignal for cancellation */

67

signal?: AbortSignal;

68

/** Request interceptor */

69

requestInterceptor?: RequestInterceptor;

70

/** Response interceptor */

71

responseInterceptor?: ResponseInterceptor;

72

/** Custom fetch function */

73

userFetch?: FetchFunction;

74

}

75

```

76

77

**Usage Examples:**

78

79

```javascript

80

import { buildRequest } from "swagger-client";

81

82

// Build request for operation

83

const request = buildRequest({

84

spec: openApiSpec,

85

operationId: "getUserById",

86

parameters: {

87

userId: "123",

88

include: ["profile", "settings"]

89

}

90

});

91

console.log(request.url); // https://api.example.com/users/123?include=profile&include=settings

92

93

// Build request with custom base URL

94

const request = buildRequest({

95

spec: openApiSpec,

96

operationId: "createUser",

97

baseURL: "https://api-staging.example.com",

98

parameters: {

99

body: {

100

name: "John Doe",

101

email: "john@example.com"

102

}

103

}

104

});

105

106

// Build request with security

107

const request = buildRequest({

108

spec: openApiSpec,

109

operationId: "getProtectedData",

110

securities: {

111

authorized: {

112

ApiKeyAuth: { value: "your-api-key" }

113

}

114

}

115

});

116

console.log(request.headers.Authorization); // Bearer your-api-key

117

```

118

119

### Parameter Handling

120

121

Handle different parameter types and locations for both OpenAPI versions.

122

123

```javascript { .api }

124

interface ParameterValues {

125

/** Parameter values by name */

126

[parameterName: string]: any;

127

/** Alternative format: parameter values by location and name */

128

[locationAndName: string]: any; // e.g., "query.limit", "header.authorization"

129

}

130

131

interface ParameterBuilders {

132

/** Build path parameters */

133

path?: ParameterBuilder;

134

/** Build query parameters */

135

query?: ParameterBuilder;

136

/** Build header parameters */

137

header?: ParameterBuilder;

138

/** Build cookie parameters (OpenAPI 3.x) */

139

cookie?: ParameterBuilder;

140

/** Build form data parameters (Swagger 2.0) */

141

formData?: ParameterBuilder;

142

/** Build request body (Swagger 2.0) */

143

body?: ParameterBuilder;

144

}

145

146

interface ParameterBuilder {

147

(options: ParameterBuildOptions): void;

148

}

149

150

interface ParameterBuildOptions {

151

/** Request object being built */

152

req: RequestObject;

153

/** Parameter definition from spec */

154

parameter: ParameterObject;

155

/** Parameter value */

156

value: any;

157

/** Operation object */

158

operation: OperationObject;

159

/** Full OpenAPI spec */

160

spec: object;

161

/** Base URL being used */

162

baseURL: string;

163

}

164

```

165

166

### Path Parameters

167

168

Replace path templates with parameter values.

169

170

```javascript { .api }

171

// Path parameter examples

172

const request = buildRequest({

173

spec: openApiSpec,

174

operationId: "getUserPosts", // GET /users/{userId}/posts/{postId}

175

parameters: {

176

userId: "123",

177

postId: "456"

178

}

179

});

180

// Results in: /users/123/posts/456

181

182

// Path parameter encoding

183

const request = buildRequest({

184

spec: openApiSpec,

185

operationId: "getFileByPath", // GET /files/{filePath}

186

parameters: {

187

filePath: "documents/my file.pdf"

188

}

189

});

190

// Results in: /files/documents%2Fmy%20file.pdf

191

```

192

193

### Query Parameters

194

195

Build query strings from parameter objects with proper encoding.

196

197

```javascript { .api }

198

// Simple query parameters

199

const request = buildRequest({

200

spec: openApiSpec,

201

operationId: "searchUsers",

202

parameters: {

203

q: "john doe",

204

limit: 10,

205

offset: 20,

206

active: true

207

}

208

});

209

// Results in: ?q=john%20doe&limit=10&offset=20&active=true

210

211

// Array query parameters (OpenAPI 3.x style serialization)

212

const request = buildRequest({

213

spec: openApiSpec,

214

operationId: "getItems",

215

parameters: {

216

tags: ["javascript", "tutorial"],

217

categories: [1, 2, 3]

218

}

219

});

220

// Results in: ?tags=javascript&tags=tutorial&categories=1&categories=2&categories=3

221

222

// Object query parameters (exploded)

223

const request = buildRequest({

224

spec: openApiSpec,

225

operationId: "searchWithFilters",

226

parameters: {

227

filters: {

228

type: "article",

229

status: "published",

230

year: 2023

231

}

232

}

233

});

234

// Results in: ?type=article&status=published&year=2023

235

```

236

237

### Header Parameters

238

239

Add custom headers from parameter definitions.

240

241

```javascript { .api }

242

// Header parameters

243

const request = buildRequest({

244

spec: openApiSpec,

245

operationId: "getLocalized",

246

parameters: {

247

"Accept-Language": "en-US,en;q=0.9",

248

"X-Client-Version": "1.2.3",

249

"If-None-Match": '"etag-value"'

250

}

251

});

252

console.log(request.headers["Accept-Language"]); // en-US,en;q=0.9

253

console.log(request.headers["X-Client-Version"]); // 1.2.3

254

255

// Header parameter encoding

256

const request = buildRequest({

257

spec: openApiSpec,

258

operationId: "searchWithHeader",

259

parameters: {

260

"X-Search-Query": "complex query with spaces & symbols"

261

}

262

});

263

// Header value is properly encoded

264

```

265

266

### Cookie Parameters (OpenAPI 3.x)

267

268

Handle cookie parameters in OpenAPI 3.x specifications.

269

270

```javascript { .api }

271

// Cookie parameters

272

const request = buildRequest({

273

spec: openApi3Spec,

274

operationId: "getPreferences",

275

parameters: {

276

sessionId: "abc123",

277

theme: "dark",

278

locale: "en-US"

279

}

280

});

281

console.log(request.headers.Cookie); // sessionId=abc123; theme=dark; locale=en-US

282

```

283

284

### Request Body (OpenAPI 3.x)

285

286

Handle request bodies with content type negotiation.

287

288

```javascript { .api }

289

// JSON request body

290

const request = buildRequest({

291

spec: openApi3Spec,

292

operationId: "createUser",

293

parameters: {

294

body: {

295

name: "John Doe",

296

email: "john@example.com",

297

age: 30

298

}

299

}

300

});

301

console.log(request.headers["Content-Type"]); // application/json

302

console.log(JSON.parse(request.body)); // { name: "John Doe", ... }

303

304

// Form data request body

305

const request = buildRequest({

306

spec: openApi3Spec,

307

operationId: "uploadProfile",

308

parameters: {

309

body: {

310

avatar: fileObject,

311

description: "Profile picture"

312

}

313

}

314

});

315

console.log(request.headers["Content-Type"]); // multipart/form-data; boundary=...

316

console.log(request.body instanceof FormData); // true

317

318

// Text request body

319

const request = buildRequest({

320

spec: openApi3Spec,

321

operationId: "updateDescription",

322

parameters: {

323

body: "This is a plain text description"

324

}

325

});

326

console.log(request.headers["Content-Type"]); // text/plain

327

```

328

329

### Form Data Parameters (Swagger 2.0)

330

331

Handle form data parameters in Swagger 2.0 specifications.

332

333

```javascript { .api }

334

// Form data parameters

335

const request = buildRequest({

336

spec: swagger2Spec,

337

operationId: "uploadFile",

338

parameters: {

339

file: fileObject,

340

description: "Document upload",

341

category: "legal"

342

}

343

});

344

console.log(request.body instanceof FormData); // true

345

346

// URL-encoded form data

347

const request = buildRequest({

348

spec: swagger2Spec,

349

operationId: "submitForm",

350

parameters: {

351

name: "John Doe",

352

email: "john@example.com",

353

subscribe: true

354

}

355

});

356

console.log(request.headers["Content-Type"]); // application/x-www-form-urlencoded

357

console.log(request.body); // name=John%20Doe&email=john%40example.com&subscribe=true

358

```

359

360

### Base URL Resolution

361

362

Compute base URLs for different OpenAPI versions and configurations.

363

364

```javascript { .api }

365

/**

366

* Compute base URL for operation

367

* @param options - Base URL computation options

368

* @returns Computed base URL

369

*/

370

function baseUrl(options: BaseUrlOptions): string;

371

372

interface BaseUrlOptions {

373

/** OpenAPI specification */

374

spec: object;

375

/** Context URL for resolution */

376

contextUrl?: string;

377

/** URL scheme override (Swagger 2.0) */

378

scheme?: string;

379

/** Server URL override (OpenAPI 3.x) */

380

server?: string;

381

/** Server variables (OpenAPI 3.x) */

382

serverVariables?: Record<string, string>;

383

/** Path name for server selection */

384

pathName?: string;

385

/** HTTP method for server selection */

386

method?: string;

387

/** Server variable encoder */

388

serverVariableEncoder?: (value: string) => string;

389

}

390

```

391

392

**Base URL Examples:**

393

394

```javascript

395

// Swagger 2.0 base URL

396

const baseURL = baseUrl({

397

spec: {

398

host: "api.example.com",

399

basePath: "/v1",

400

schemes: ["https"]

401

}

402

});

403

console.log(baseURL); // https://api.example.com/v1

404

405

// OpenAPI 3.x base URL

406

const baseURL = baseUrl({

407

spec: {

408

servers: [

409

{ url: "https://api.example.com/v1" },

410

{ url: "https://staging-api.example.com/v1" }

411

]

412

}

413

});

414

console.log(baseURL); // https://api.example.com/v1

415

416

// OpenAPI 3.x with server variables

417

const baseURL = baseUrl({

418

spec: {

419

servers: [

420

{

421

url: "https://{environment}.example.com/{version}",

422

variables: {

423

environment: { default: "api" },

424

version: { default: "v1" }

425

}

426

}

427

]

428

},

429

serverVariables: {

430

environment: "staging",

431

version: "v2"

432

}

433

});

434

console.log(baseURL); // https://staging.example.com/v2

435

```

436

437

### Security Application

438

439

Apply security requirements to requests.

440

441

```javascript { .api }

442

interface SecurityRequirements {

443

authorized?: SecurityAuthorizations;

444

}

445

446

interface SecurityAuthorizations {

447

[securityName: string]: SecurityValue;

448

}

449

450

interface SecurityValue {

451

username?: string;

452

password?: string;

453

clientId?: string;

454

clientSecret?: string;

455

value?: string;

456

}

457

```

458

459

**Security Examples:**

460

461

```javascript

462

// API Key in header

463

const request = buildRequest({

464

spec: openApiSpec,

465

operationId: "getProtectedData",

466

securities: {

467

authorized: {

468

ApiKeyAuth: { value: "your-api-key" }

469

}

470

}

471

});

472

console.log(request.headers["X-API-Key"]); // your-api-key

473

474

// Bearer token

475

const request = buildRequest({

476

spec: openApiSpec,

477

operationId: "getProtectedData",

478

securities: {

479

authorized: {

480

BearerAuth: { value: "jwt-token-here" }

481

}

482

}

483

});

484

console.log(request.headers.Authorization); // Bearer jwt-token-here

485

486

// Basic authentication

487

const request = buildRequest({

488

spec: openApiSpec,

489

operationId: "getProtectedData",

490

securities: {

491

authorized: {

492

BasicAuth: {

493

username: "user",

494

password: "password"

495

}

496

}

497

}

498

});

499

console.log(request.headers.Authorization); // Basic dXNlcjpwYXNzd29yZA==

500

```

501

502

### Parameter Validation

503

504

Handle parameter validation and default values.

505

506

```javascript { .api }

507

// Required parameter validation

508

try {

509

const request = buildRequest({

510

spec: openApiSpec,

511

operationId: "getUserById",

512

parameters: {} // Missing required userId parameter

513

});

514

} catch (error) {

515

console.error(error.message); // "Required parameter userId is not provided"

516

}

517

518

// Default parameter values

519

const request = buildRequest({

520

spec: openApiSpec,

521

operationId: "searchUsers",

522

parameters: {

523

q: "john"

524

// limit parameter has default value of 10 in spec

525

}

526

});

527

console.log(request.url); // includes limit=10 from default value

528

529

// Parameter type coercion (OpenAPI 3.x)

530

const request = buildRequest({

531

spec: openApi3Spec,

532

operationId: "getItems",

533

parameters: {

534

filters: '{"type": "article", "status": "published"}' // JSON string

535

}

536

});

537

// String is parsed to object based on parameter schema

538

```

539

540

## Common Types

541

542

```javascript { .api }

543

interface ParameterObject {

544

name: string;

545

in: "query" | "header" | "path" | "cookie" | "body" | "formData";

546

required?: boolean;

547

schema?: SchemaObject;

548

style?: string;

549

explode?: boolean;

550

allowEmptyValue?: boolean;

551

default?: any;

552

}

553

554

interface OperationObject {

555

operationId?: string;

556

parameters?: ParameterObject[];

557

requestBody?: RequestBodyObject;

558

security?: SecurityRequirement[];

559

servers?: ServerObject[];

560

}

561

562

interface RequestInterceptor {

563

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

564

}

565

566

interface ResponseInterceptor {

567

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

568

}

569

570

interface HttpClient {

571

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

572

withCredentials?: boolean;

573

}

574

575

interface FetchFunction {

576

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

577

}

578

```