CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-oas

Comprehensive tooling for working with OpenAPI definitions

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

parameter-handling-json-schema.mddocs/

Parameter Handling and JSON Schema

Parameter extraction, JSON Schema conversion, and type-safe parameter processing for OpenAPI operations.

Capabilities

Get Operation Parameters

Retrieve all parameters (path, query, header, cookie) for an operation.

/**
 * Get all parameters for this operation
 * @returns Array of parameter objects including inherited common parameters
 */
getParameters(): ParameterObject[];

Usage Examples:

const operation = oas.operation("/users/{id}", "get");
const parameters = operation.getParameters();

parameters.forEach(param => {
  console.log(`${param.name} (${param.in}): ${param.required ? 'required' : 'optional'}`);
  console.log(`  Type: ${param.schema?.type}`);
  console.log(`  Description: ${param.description || 'N/A'}`);
});

// Filter by parameter location
const pathParams = parameters.filter(p => p.in === 'path');
const queryParams = parameters.filter(p => p.in === 'query');
const headerParams = parameters.filter(p => p.in === 'header');

Check Parameter Existence

Determine if an operation has any parameters or required parameters.

/**
 * Check if operation has any parameters
 * @returns True if operation has parameters
 */
hasParameters(): boolean;

/**
 * Check if operation has required parameters
 * @returns True if any parameters are marked as required
 */
hasRequiredParameters(): boolean;

Usage Examples:

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

if (operation.hasParameters()) {
  console.log("Operation has parameters");
  
  if (operation.hasRequiredParameters()) {
    console.log("Some parameters are required");
    
    // Find required parameters
    const required = operation.getParameters().filter(p => p.required);
    console.log(`Required: ${required.map(p => p.name).join(', ')}`);
  }
}

Convert Parameters to JSON Schema

Convert operation parameters to JSON Schema format for validation and form generation.

/**
 * Convert operation parameters to JSON Schema format
 * @param opts - Options for schema conversion
 * @returns Array of schema wrappers organized by parameter type
 */
getParametersAsJSONSchema(opts?: getParametersAsJSONSchemaOptions): SchemaWrapper[];

interface getParametersAsJSONSchemaOptions {
  /** Global default values for parameters */
  globalDefaults?: Record<string, unknown>;
  /** Hide readOnly properties */
  hideReadOnlyProperties?: boolean;
  /** Hide writeOnly properties */
  hideWriteOnlyProperties?: boolean;
  /** Include discriminator mapping refs */
  includeDiscriminatorMappingRefs?: boolean;
  /** Schema transformation function */
  transformer?: (schema: SchemaObject) => SchemaObject;
}

interface SchemaWrapper {
  /** JSON Schema version */
  $schema?: string;
  /** Deprecated properties schema */
  deprecatedProps?: SchemaWrapper;
  /** Schema description */
  description?: string;
  /** Display label */
  label?: string;
  /** JSON Schema object */
  schema: SchemaObject;
  /** Parameter type (path, query, header, etc.) */
  type: string;
}

Usage Examples:

const operation = oas.operation("/users/{id}", "get");
const schemas = operation.getParametersAsJSONSchema();

schemas.forEach(schemaWrapper => {
  console.log(`\n${schemaWrapper.type} (${schemaWrapper.label}):`);
  console.log(`Description: ${schemaWrapper.description || 'N/A'}`);
  
  if (schemaWrapper.schema.properties) {
    Object.entries(schemaWrapper.schema.properties).forEach(([name, prop]) => {
      const required = schemaWrapper.schema.required?.includes(name) ? ' (required)' : '';
      console.log(`  ${name}${required}: ${prop.type || 'object'}`);
    });
  }
});

// Use with form validation
const pathSchema = schemas.find(s => s.type === 'path');
if (pathSchema) {
  // Validate path parameters
  const pathData = { id: "123" };
  // Use with JSON Schema validator library
}

Advanced Schema Conversion

// With global defaults
const schemasWithDefaults = operation.getParametersAsJSONSchema({
  globalDefaults: {
    limit: 10,
    offset: 0,
    format: 'json'
  }
});

// Hide sensitive properties
const publicSchemas = operation.getParametersAsJSONSchema({
  hideReadOnlyProperties: true,
  hideWriteOnlyProperties: true
});

// Transform schemas
const transformedSchemas = operation.getParametersAsJSONSchema({
  transformer: (schema) => {
    // Add custom validation
    if (schema.type === 'string') {
      schema.minLength = schema.minLength || 1;
    }
    return schema;
  }
});

Parameter Types and Organization

Parameter Type Constants

/** Parameter type labels for organization */
const types: Record<string, string> = {
  path: 'Path Params',
  query: 'Query Params', 
  body: 'Body Params',
  cookie: 'Cookie Params',
  formData: 'Form Data',
  header: 'Headers',
  metadata: 'Metadata'
};

Parameter Type Interfaces

interface ParameterObject {
  /** Parameter location */
  in: 'cookie' | 'header' | 'path' | 'query';
  /** Parameter name */
  name: string;
  /** Parameter description */  
  description?: string;
  /** Whether parameter is required */
  required?: boolean;
  /** Parameter schema */
  schema?: SchemaObject;
  /** Parameter style (for serialization) */
  style?: string;
  /** Whether to explode array/object parameters */
  explode?: boolean;
  /** Whether to allow empty values */
  allowEmptyValue?: boolean;
  /** Deprecated flag */
  deprecated?: boolean;
  /** Example value */
  example?: any;
  /** Multiple examples */
  examples?: Record<string, ExampleObject>;
}

Advanced Parameter Handling

Common Parameter Inheritance

Parameters defined at the path level are automatically inherited by all operations:

// Path-level parameters are merged with operation parameters
const pathItem = {
  parameters: [
    { name: "version", in: "header", required: true, schema: { type: "string" } }
  ],
  get: {
    parameters: [
      { name: "id", in: "path", required: true, schema: { type: "string" } }
    ]
  }
};

// getParameters() returns both version (from path) and id (from operation)
const allParams = operation.getParameters(); // [version, id]

Parameter Deduplication

The library automatically deduplicates parameters, with operation-level parameters taking precedence:

// If both path and operation define the same parameter name,
// the operation-level definition wins
const pathParams = [{ name: "limit", in: "query", schema: { type: "number", default: 20 } }];
const opParams = [{ name: "limit", in: "query", schema: { type: "number", default: 10 } }];

// Result: limit defaults to 10 (operation wins)

Parameter Serialization Styles

Handle different parameter serialization styles for arrays and objects:

// Different serialization styles
const arrayParam = {
  name: "tags",
  in: "query", 
  schema: { type: "array", items: { type: "string" } },
  style: "form",    // tags=red,green,blue
  explode: false
};

const objectParam = {
  name: "filter",
  in: "query",
  schema: { type: "object" },
  style: "deepObject",  // filter[name]=john&filter[age]=30
  explode: true
};

Schema Generation for Different Use Cases

// Form generation
const formSchemas = operation.getParametersAsJSONSchema({
  hideReadOnlyProperties: true
});

// Documentation generation  
const docSchemas = operation.getParametersAsJSONSchema({
  includeDiscriminatorMappingRefs: true
});

// Validation schemas
const validationSchemas = operation.getParametersAsJSONSchema({
  transformer: (schema) => {
    // Remove examples for validation
    delete schema.example;
    delete schema.examples;
    return schema;
  }
});

Error Handling

Parameter handling gracefully manages various edge cases:

  • Missing Parameters: Operations without parameters return empty arrays
  • Invalid References: Broken $ref pointers are handled gracefully
  • Type Conflicts: Schema transformation handles type inconsistencies
  • Circular References: Schema conversion prevents infinite loops
const operation = oas.operation("/nonexistent", "get");
const params = operation.getParameters(); // Returns [] for missing operations

// Schema conversion handles errors gracefully
const schemas = operation.getParametersAsJSONSchema();
// Returns valid schemas even with problematic parameter definitions

Install with Tessl CLI

npx tessl i tessl/npm-oas

docs

analysis-metrics.md

api-definition-reduction.md

extensions-customization.md

index.md

openapi-definition-management.md

operation-discovery-analysis.md

parameter-handling-json-schema.md

request-response-management.md

schema-dereferencing-references.md

security-authentication.md

server-url-management.md

utils.md

tile.json