or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

analysis-metrics.mdapi-definition-reduction.mdextensions-customization.mdindex.mdopenapi-definition-management.mdoperation-discovery-analysis.mdparameter-handling-json-schema.mdrequest-response-management.mdschema-dereferencing-references.mdsecurity-authentication.mdserver-url-management.mdutils.md

request-response-management.mddocs/

0

# Request and Response Management

1

2

Comprehensive request body and response handling with content type detection, schema conversion, and example extraction.

3

4

## Capabilities

5

6

### Request Body Handling

7

8

#### Check Request Body Existence

9

10

```typescript { .api }

11

/**

12

* Check if operation has a request body

13

* @returns True if operation defines a request body

14

*/

15

hasRequestBody(): boolean;

16

17

/**

18

* Check if request body is required

19

* @returns True if request body is marked as required or has required properties

20

*/

21

hasRequiredRequestBody(): boolean;

22

```

23

24

**Usage Examples:**

25

26

```typescript

27

const operation = oas.operation("/users", "post");

28

29

if (operation.hasRequestBody()) {

30

console.log("Operation accepts request body");

31

32

if (operation.hasRequiredRequestBody()) {

33

console.log("Request body is required");

34

}

35

}

36

```

37

38

#### Get Request Body Media Types

39

40

```typescript { .api }

41

/**

42

* Get all available media types for the request body

43

* @returns Array of media type strings (e.g., ["application/json", "multipart/form-data"])

44

*/

45

getRequestBodyMediaTypes(): string[];

46

```

47

48

**Usage Examples:**

49

50

```typescript

51

const mediaTypes = operation.getRequestBodyMediaTypes();

52

console.log("Supported media types:", mediaTypes);

53

54

// Check for specific formats

55

const supportsJson = mediaTypes.some(type => type.includes("json"));

56

const supportsFormData = mediaTypes.some(type => type.includes("form-data"));

57

const supportsXml = mediaTypes.some(type => type.includes("xml"));

58

```

59

60

#### Get Request Body Content

61

62

```typescript { .api }

63

/**

64

* Get request body content for a specific media type

65

* @param mediaType - Specific media type to retrieve (optional)

66

* @returns Media type object, or array with selected type and description, or false if not found

67

*/

68

getRequestBody(mediaType?: string): MediaTypeObject | false | [string, MediaTypeObject, ...string[]];

69

```

70

71

**Usage Examples:**

72

73

```typescript

74

// Get specific media type

75

const jsonBody = operation.getRequestBody("application/json");

76

if (jsonBody && typeof jsonBody === 'object' && 'schema' in jsonBody) {

77

console.log("JSON schema:", jsonBody.schema);

78

}

79

80

// Auto-select best media type (prefers JSON)

81

const autoBody = operation.getRequestBody();

82

if (Array.isArray(autoBody)) {

83

const [selectedType, mediaTypeObj, description] = autoBody;

84

console.log(`Selected: ${selectedType}`);

85

console.log(`Schema:`, mediaTypeObj.schema);

86

if (description) console.log(`Description: ${description}`);

87

}

88

89

// Handle missing request body

90

const noBody = operation.getRequestBody("text/plain");

91

if (noBody === false) {

92

console.log("Media type not supported");

93

}

94

```

95

96

#### Get Request Body Examples

97

98

```typescript { .api }

99

/**

100

* Get request body examples for this operation

101

* @returns Array of request body examples with metadata

102

*/

103

getRequestBodyExamples(): RequestBodyExamples;

104

```

105

106

**Usage Examples:**

107

108

```typescript

109

const examples = operation.getRequestBodyExamples();

110

111

examples.forEach(example => {

112

console.log(`Media type: ${example.mediaType}`);

113

114

example.examples.forEach(ex => {

115

console.log(`Example: ${ex.key || 'default'}`);

116

console.log(`Value:`, JSON.stringify(ex.value, null, 2));

117

if (ex.summary) console.log(`Summary: ${ex.summary}`);

118

});

119

});

120

```

121

122

### Response Handling

123

124

#### Get Response Status Codes

125

126

```typescript { .api }

127

/**

128

* Get all defined response status codes for this operation

129

* @returns Array of status code strings (e.g., ["200", "400", "404", "default"])

130

*/

131

getResponseStatusCodes(): string[];

132

```

133

134

**Usage Examples:**

135

136

```typescript

137

const statusCodes = operation.getResponseStatusCodes();

138

console.log("Defined responses:", statusCodes);

139

140

// Categorize responses

141

const successCodes = statusCodes.filter(code => code.startsWith('2'));

142

const errorCodes = statusCodes.filter(code => code.startsWith('4') || code.startsWith('5'));

143

const hasDefault = statusCodes.includes('default');

144

```

145

146

#### Get Response by Status Code

147

148

```typescript { .api }

149

/**

150

* Get response object for a specific status code

151

* @param statusCode - Status code to retrieve (number or string)

152

* @returns Response object or false if not found

153

*/

154

getResponseByStatusCode(statusCode: number | string): ResponseObject | boolean;

155

```

156

157

**Usage Examples:**

158

159

```typescript

160

// Get success response

161

const successResponse = operation.getResponseByStatusCode(200);

162

if (successResponse && typeof successResponse === 'object') {

163

console.log("Success description:", successResponse.description);

164

165

if (successResponse.content) {

166

console.log("Response content types:", Object.keys(successResponse.content));

167

}

168

169

if (successResponse.headers) {

170

console.log("Response headers:", Object.keys(successResponse.headers));

171

}

172

}

173

174

// Get error response

175

const errorResponse = operation.getResponseByStatusCode("400");

176

if (errorResponse) {

177

console.log("Error response defined");

178

}

179

180

// Handle missing response

181

const missing = operation.getResponseByStatusCode(418);

182

if (missing === false) {

183

console.log("Status code not defined");

184

}

185

```

186

187

#### Get Response as JSON Schema

188

189

```typescript { .api }

190

/**

191

* Convert response to JSON Schema format

192

* @param statusCode - Status code to convert

193

* @param opts - Conversion options

194

* @returns JSON Schema representation of the response

195

*/

196

getResponseAsJSONSchema(

197

statusCode: number | string,

198

opts?: {

199

includeDiscriminatorMappingRefs?: boolean;

200

transformer?: (schema: SchemaObject) => SchemaObject;

201

}

202

): SchemaObject;

203

```

204

205

**Usage Examples:**

206

207

```typescript

208

// Get response schema

209

const responseSchema = operation.getResponseAsJSONSchema(200);

210

console.log("Response schema:", responseSchema);

211

212

// With transformation

213

const transformedSchema = operation.getResponseAsJSONSchema(200, {

214

transformer: (schema) => {

215

// Add validation metadata

216

schema.additionalProperties = false;

217

return schema;

218

}

219

});

220

221

// For multiple content types, schema represents the first JSON-like type

222

const schema = operation.getResponseAsJSONSchema("200");

223

if (schema.type === 'object') {

224

console.log("Response properties:", Object.keys(schema.properties || {}));

225

}

226

```

227

228

#### Get Response Examples

229

230

```typescript { .api }

231

/**

232

* Get response examples for this operation

233

* @returns Array of response examples organized by status code and media type

234

*/

235

getResponseExamples(): ResponseExamples;

236

```

237

238

**Usage Examples:**

239

240

```typescript

241

const responseExamples = operation.getResponseExamples();

242

243

responseExamples.forEach(example => {

244

console.log(`Status: ${example.status}`);

245

console.log(`Media type: ${example.mediaType}`);

246

247

example.examples.forEach(ex => {

248

console.log(`Example: ${ex.key || 'default'}`);

249

console.log(`Value:`, JSON.stringify(ex.value, null, 2));

250

if (ex.summary) console.log(`Summary: ${ex.summary}`);

251

});

252

});

253

```

254

255

### Header Management

256

257

#### Get Request and Response Headers

258

259

```typescript { .api }

260

/**

261

* Get all request and response headers for this operation

262

* @returns Object with request and response header arrays

263

*/

264

getHeaders(): {

265

request: string[];

266

response: string[];

267

};

268

```

269

270

**Usage Examples:**

271

272

```typescript

273

const headers = operation.getHeaders();

274

275

console.log("Request headers:");

276

headers.request.forEach(header => {

277

console.log(` ${header}`);

278

});

279

280

console.log("Response headers:");

281

headers.response.forEach(header => {

282

console.log(` ${header}`);

283

});

284

285

// Check for specific headers

286

const hasAuth = headers.request.includes('Authorization');

287

const hasContentType = headers.request.includes('Content-Type');

288

const hasAccept = headers.request.includes('Accept');

289

```

290

291

## Advanced Response Handling

292

293

### Multi-Content Type Responses

294

295

```typescript

296

// Handle operations with multiple response content types

297

const response = operation.getResponseByStatusCode(200);

298

if (response && typeof response === 'object' && response.content) {

299

const contentTypes = Object.keys(response.content);

300

301

contentTypes.forEach(contentType => {

302

const mediaTypeObj = response.content[contentType];

303

console.log(`${contentType}:`, mediaTypeObj.schema);

304

305

// Get examples for this content type

306

if (mediaTypeObj.examples) {

307

Object.entries(mediaTypeObj.examples).forEach(([key, example]) => {

308

console.log(` Example ${key}:`, example.value);

309

});

310

}

311

});

312

}

313

```

314

315

### Error Response Patterns

316

317

```typescript

318

// Analyze error response patterns

319

const errorCodes = operation.getResponseStatusCodes()

320

.filter(code => code.startsWith('4') || code.startsWith('5'));

321

322

errorCodes.forEach(code => {

323

const errorResponse = operation.getResponseByStatusCode(code);

324

if (errorResponse && typeof errorResponse === 'object') {

325

console.log(`Error ${code}: ${errorResponse.description}`);

326

327

// Get error schema

328

const errorSchema = operation.getResponseAsJSONSchema(code);

329

if (errorSchema.properties) {

330

console.log("Error fields:", Object.keys(errorSchema.properties));

331

}

332

}

333

});

334

```

335

336

### Content Negotiation

337

338

```typescript

339

// Handle content negotiation

340

const requestTypes = operation.getRequestBodyMediaTypes();

341

const responseTypes = operation.getResponseStatusCodes()

342

.map(code => {

343

const response = operation.getResponseByStatusCode(code);

344

if (response && typeof response === 'object' && response.content) {

345

return Object.keys(response.content);

346

}

347

return [];

348

})

349

.flat();

350

351

console.log("Accepts:", requestTypes);

352

console.log("Produces:", [...new Set(responseTypes)]);

353

```

354

355

## Type Definitions

356

357

```typescript { .api }

358

interface RequestBodyExamples {

359

mediaType: string;

360

examples: Array<{

361

key?: string;

362

value: any;

363

summary?: string;

364

description?: string;

365

}>;

366

}

367

368

interface ResponseExamples {

369

status: string;

370

mediaType: string;

371

examples: Array<{

372

key?: string;

373

value: any;

374

summary?: string;

375

description?: string;

376

}>;

377

}

378

379

interface MediaTypeObject {

380

schema?: SchemaObject;

381

example?: any;

382

examples?: Record<string, ExampleObject>;

383

encoding?: Record<string, EncodingObject>;

384

}

385

386

interface ResponseObject {

387

description: string;

388

headers?: Record<string, HeaderObject>;

389

content?: Record<string, MediaTypeObject>;

390

links?: Record<string, LinkObject>;

391

}

392

```

393

394

## Error Handling

395

396

Request and response handling gracefully manages various scenarios:

397

398

- **Missing Bodies**: Methods return `false` or empty arrays for missing request/response bodies

399

- **Invalid Content Types**: Unknown media types are handled gracefully

400

- **Schema Conversion**: Malformed schemas are converted to valid JSON Schema where possible

401

- **Circular References**: Schema conversion prevents infinite loops in recursive schemas

402

403

```typescript

404

// Safe handling of missing data

405

const operation = oas.operation("/nonexistent", "get");

406

407

const hasBody = operation.hasRequestBody(); // false

408

const mediaTypes = operation.getRequestBodyMediaTypes(); // []

409

const examples = operation.getRequestBodyExamples(); // []

410

const statusCodes = operation.getResponseStatusCodes(); // []

411

```