docs
0
# Parameter Handling and JSON Schema
1
2
Parameter extraction, JSON Schema conversion, and type-safe parameter processing for OpenAPI operations.
3
4
## Capabilities
5
6
### Get Operation Parameters
7
8
Retrieve all parameters (path, query, header, cookie) for an operation.
9
10
```typescript { .api }
11
/**
12
* Get all parameters for this operation
13
* @returns Array of parameter objects including inherited common parameters
14
*/
15
getParameters(): ParameterObject[];
16
```
17
18
**Usage Examples:**
19
20
```typescript
21
const operation = oas.operation("/users/{id}", "get");
22
const parameters = operation.getParameters();
23
24
parameters.forEach(param => {
25
console.log(`${param.name} (${param.in}): ${param.required ? 'required' : 'optional'}`);
26
console.log(` Type: ${param.schema?.type}`);
27
console.log(` Description: ${param.description || 'N/A'}`);
28
});
29
30
// Filter by parameter location
31
const pathParams = parameters.filter(p => p.in === 'path');
32
const queryParams = parameters.filter(p => p.in === 'query');
33
const headerParams = parameters.filter(p => p.in === 'header');
34
```
35
36
### Check Parameter Existence
37
38
Determine if an operation has any parameters or required parameters.
39
40
```typescript { .api }
41
/**
42
* Check if operation has any parameters
43
* @returns True if operation has parameters
44
*/
45
hasParameters(): boolean;
46
47
/**
48
* Check if operation has required parameters
49
* @returns True if any parameters are marked as required
50
*/
51
hasRequiredParameters(): boolean;
52
```
53
54
**Usage Examples:**
55
56
```typescript
57
const operation = oas.operation("/users", "get");
58
59
if (operation.hasParameters()) {
60
console.log("Operation has parameters");
61
62
if (operation.hasRequiredParameters()) {
63
console.log("Some parameters are required");
64
65
// Find required parameters
66
const required = operation.getParameters().filter(p => p.required);
67
console.log(`Required: ${required.map(p => p.name).join(', ')}`);
68
}
69
}
70
```
71
72
### Convert Parameters to JSON Schema
73
74
Convert operation parameters to JSON Schema format for validation and form generation.
75
76
```typescript { .api }
77
/**
78
* Convert operation parameters to JSON Schema format
79
* @param opts - Options for schema conversion
80
* @returns Array of schema wrappers organized by parameter type
81
*/
82
getParametersAsJSONSchema(opts?: getParametersAsJSONSchemaOptions): SchemaWrapper[];
83
84
interface getParametersAsJSONSchemaOptions {
85
/** Global default values for parameters */
86
globalDefaults?: Record<string, unknown>;
87
/** Hide readOnly properties */
88
hideReadOnlyProperties?: boolean;
89
/** Hide writeOnly properties */
90
hideWriteOnlyProperties?: boolean;
91
/** Include discriminator mapping refs */
92
includeDiscriminatorMappingRefs?: boolean;
93
/** Schema transformation function */
94
transformer?: (schema: SchemaObject) => SchemaObject;
95
}
96
97
interface SchemaWrapper {
98
/** JSON Schema version */
99
$schema?: string;
100
/** Deprecated properties schema */
101
deprecatedProps?: SchemaWrapper;
102
/** Schema description */
103
description?: string;
104
/** Display label */
105
label?: string;
106
/** JSON Schema object */
107
schema: SchemaObject;
108
/** Parameter type (path, query, header, etc.) */
109
type: string;
110
}
111
```
112
113
**Usage Examples:**
114
115
```typescript
116
const operation = oas.operation("/users/{id}", "get");
117
const schemas = operation.getParametersAsJSONSchema();
118
119
schemas.forEach(schemaWrapper => {
120
console.log(`\n${schemaWrapper.type} (${schemaWrapper.label}):`);
121
console.log(`Description: ${schemaWrapper.description || 'N/A'}`);
122
123
if (schemaWrapper.schema.properties) {
124
Object.entries(schemaWrapper.schema.properties).forEach(([name, prop]) => {
125
const required = schemaWrapper.schema.required?.includes(name) ? ' (required)' : '';
126
console.log(` ${name}${required}: ${prop.type || 'object'}`);
127
});
128
}
129
});
130
131
// Use with form validation
132
const pathSchema = schemas.find(s => s.type === 'path');
133
if (pathSchema) {
134
// Validate path parameters
135
const pathData = { id: "123" };
136
// Use with JSON Schema validator library
137
}
138
```
139
140
### Advanced Schema Conversion
141
142
```typescript
143
// With global defaults
144
const schemasWithDefaults = operation.getParametersAsJSONSchema({
145
globalDefaults: {
146
limit: 10,
147
offset: 0,
148
format: 'json'
149
}
150
});
151
152
// Hide sensitive properties
153
const publicSchemas = operation.getParametersAsJSONSchema({
154
hideReadOnlyProperties: true,
155
hideWriteOnlyProperties: true
156
});
157
158
// Transform schemas
159
const transformedSchemas = operation.getParametersAsJSONSchema({
160
transformer: (schema) => {
161
// Add custom validation
162
if (schema.type === 'string') {
163
schema.minLength = schema.minLength || 1;
164
}
165
return schema;
166
}
167
});
168
```
169
170
## Parameter Types and Organization
171
172
### Parameter Type Constants
173
174
```typescript { .api }
175
/** Parameter type labels for organization */
176
const types: Record<string, string> = {
177
path: 'Path Params',
178
query: 'Query Params',
179
body: 'Body Params',
180
cookie: 'Cookie Params',
181
formData: 'Form Data',
182
header: 'Headers',
183
metadata: 'Metadata'
184
};
185
```
186
187
### Parameter Type Interfaces
188
189
```typescript { .api }
190
interface ParameterObject {
191
/** Parameter location */
192
in: 'cookie' | 'header' | 'path' | 'query';
193
/** Parameter name */
194
name: string;
195
/** Parameter description */
196
description?: string;
197
/** Whether parameter is required */
198
required?: boolean;
199
/** Parameter schema */
200
schema?: SchemaObject;
201
/** Parameter style (for serialization) */
202
style?: string;
203
/** Whether to explode array/object parameters */
204
explode?: boolean;
205
/** Whether to allow empty values */
206
allowEmptyValue?: boolean;
207
/** Deprecated flag */
208
deprecated?: boolean;
209
/** Example value */
210
example?: any;
211
/** Multiple examples */
212
examples?: Record<string, ExampleObject>;
213
}
214
```
215
216
## Advanced Parameter Handling
217
218
### Common Parameter Inheritance
219
220
Parameters defined at the path level are automatically inherited by all operations:
221
222
```typescript
223
// Path-level parameters are merged with operation parameters
224
const pathItem = {
225
parameters: [
226
{ name: "version", in: "header", required: true, schema: { type: "string" } }
227
],
228
get: {
229
parameters: [
230
{ name: "id", in: "path", required: true, schema: { type: "string" } }
231
]
232
}
233
};
234
235
// getParameters() returns both version (from path) and id (from operation)
236
const allParams = operation.getParameters(); // [version, id]
237
```
238
239
### Parameter Deduplication
240
241
The library automatically deduplicates parameters, with operation-level parameters taking precedence:
242
243
```typescript
244
// If both path and operation define the same parameter name,
245
// the operation-level definition wins
246
const pathParams = [{ name: "limit", in: "query", schema: { type: "number", default: 20 } }];
247
const opParams = [{ name: "limit", in: "query", schema: { type: "number", default: 10 } }];
248
249
// Result: limit defaults to 10 (operation wins)
250
```
251
252
### Parameter Serialization Styles
253
254
Handle different parameter serialization styles for arrays and objects:
255
256
```typescript
257
// Different serialization styles
258
const arrayParam = {
259
name: "tags",
260
in: "query",
261
schema: { type: "array", items: { type: "string" } },
262
style: "form", // tags=red,green,blue
263
explode: false
264
};
265
266
const objectParam = {
267
name: "filter",
268
in: "query",
269
schema: { type: "object" },
270
style: "deepObject", // filter[name]=john&filter[age]=30
271
explode: true
272
};
273
```
274
275
### Schema Generation for Different Use Cases
276
277
```typescript
278
// Form generation
279
const formSchemas = operation.getParametersAsJSONSchema({
280
hideReadOnlyProperties: true
281
});
282
283
// Documentation generation
284
const docSchemas = operation.getParametersAsJSONSchema({
285
includeDiscriminatorMappingRefs: true
286
});
287
288
// Validation schemas
289
const validationSchemas = operation.getParametersAsJSONSchema({
290
transformer: (schema) => {
291
// Remove examples for validation
292
delete schema.example;
293
delete schema.examples;
294
return schema;
295
}
296
});
297
```
298
299
## Error Handling
300
301
Parameter handling gracefully manages various edge cases:
302
303
- **Missing Parameters**: Operations without parameters return empty arrays
304
- **Invalid References**: Broken `$ref` pointers are handled gracefully
305
- **Type Conflicts**: Schema transformation handles type inconsistencies
306
- **Circular References**: Schema conversion prevents infinite loops
307
308
```typescript
309
const operation = oas.operation("/nonexistent", "get");
310
const params = operation.getParameters(); // Returns [] for missing operations
311
312
// Schema conversion handles errors gracefully
313
const schemas = operation.getParametersAsJSONSchema();
314
// Returns valid schemas even with problematic parameter definitions
315
```