npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@openapi-contrib/openapi-schema-to-json-schema

v5.1.0

Published

Converts OpenAPI Schema Object to JSON Schema

Downloads

970,834

Readme

OpenAPI Schema to JSON Schema

A little NodeJS package to convert OpenAPI Schema Object or Parameter Object to JSON Schema.

Currently converts from OpenAPI 3.0 to JSON Schema Draft 4.

Treeware

Why?

OpenAPI is a specification for describing RESTful APIs. OpenAPI v3.0 allows us to describe the structures of request and response payloads in a detailed manner. This would, theoretically, mean that we should be able to automatically validate request and response payloads. However, as of writing there aren't many validators around.

The good news is that there are many validators for JSON Schema for different languages. The bad news is that OpenAPI v3.0 is not entirely compatible with JSON Schema. The Schema Object of OpenAPI v3.0 is an extended subset of JSON Schema Specification Wright Draft 00 with some differences. This will be resolved in OpenAPI v3.1, but until then... this tool will fill that gap.

There is also a CLI tool for creating a JSON of schemas from the whole API specification.

If you need to do the conversion in reverse, checkout json-schema-to-openapi-schema.

Features

  • converts OpenAPI v3.0 Schema Object to JSON Schema Draft 4
  • converts OpenAPI v3.0 Parameter Object to JSON Schema Draft 4
  • deletes nullable and adds "null" to type array if nullable is true
  • supports deep structures with nested allOfs etc.
  • removes OpenAPI specific properties such as discriminator, deprecated etc. unless specified otherwise
  • optionally supports patternProperties with x-patternProperties in the Schema Object

NOTE: $refs are not handled in any way, so please use a resolver such as json-schema-ref-parser or swagger-cli bundle prior to using this package.

Installation

npm install --save @openapi-contrib/openapi-schema-to-json-schema

CLI

npx "@openapi-contrib/openapi-schema-to-json-schema" --input openapi.json --output json-schema.json

Converting OpenAPI schema

Here's a small example to get the idea:

var { openapiSchemaToJsonSchema: toJsonSchema } = require("@openapi-contrib/openapi-schema-to-json-schema");

var schema = {
  type: "string",
  format: "date-time",
  nullable: true,
};

var convertedSchema = toJsonSchema(schema);

console.log(convertedSchema);

The example prints out

{
  type: ['string', 'null'],
  format: 'date-time',
  '$schema': 'http://json-schema.org/draft-04/schema#'
}

Provide the function the schema object with possible options.

Options

The function accepts options object as the second argument.

cloneSchema (boolean)

If set to false, converts the provided schema in place. If true, clones the schema by converting it to JSON and back. The overhead of the cloning is usually negligible. Defaults to true.

dateToDateTime (boolean)

This is false by default and leaves date format as is. If set to true, sets format: 'date' to format: 'date-time'.

For example

var schema = {
  type: "string",
  format: "date",
};

var convertedSchema = toJsonSchema(schema, { dateToDateTime: true });

console.log(convertedSchema);

prints

{
  type: 'string',
  format: 'date-time',
  '$schema': 'http://json-schema.org/draft-04/schema#'
}

keepNotSupported (array)

By default, the following fields are removed from the result schema: nullable, discriminator, readOnly, writeOnly, xml, externalDocs, example and deprecated as they are not supported by JSON Schema Draft 4. Provide an array of the ones you want to keep (as strings) and they won't be removed.

removeReadOnly (boolean)

If set to true, will remove properties set as readOnly. If the property is set as required, it will be removed from the required array as well. The property will be removed even if readOnly is set to be kept with keepNotSupported.

removeWriteOnly (boolean)

Similar to removeReadOnly, but for writeOnly properties.

supportPatternProperties (boolean)

If set to true and x-patternProperties property is present, change x-patternProperties to patternProperties and call patternPropertiesHandler. If patternPropertiesHandler is not defined, call the default handler. See patternPropertiesHandler for more information.

patternPropertiesHandler (function)

Provide a function to handle pattern properties and set supportPatternProperties to take effect. The function takes the schema where x-patternProperties is defined on the root level. At this point x-patternProperties is changed to patternProperties. It must return the modified schema.

If the handler is not provided, the default handler is used. If additionalProperties is set and is an object, the default handler sets it to false if the additionalProperties object has deep equality with a pattern object inside patternProperties. This is because we might want to define additionalProperties in OpenAPI spec file, but want to validate against a pattern. The pattern would turn out to be useless if additionalProperties of the same structure were allowed. Create you own handler to override this functionality.

See test/pattern_properties.test.js for examples how this works.

definitionKeywords (array)

By default, definitions are not converted. If your documents follow the convention of having a definitions object at the root of a (sub)schema, you can set definitionKeywords to ['definitions'].

var schema = {
  definitions: {
    sharedDefinition: {
      type: "object",
      properties: {
        foo: {
          type: "string",
          nullable: true,
        },
      },
    },
  },
};
var convertedSchema = toJsonSchema(schema, {
  definitionKeywords: ["definitions"],
});
console.log(convertedSchema);

prints

{
  $schema: 'http://json-schema.org/draft-04/schema#',
  definitions: {
    sharedDefinition: {
      type: 'object',
      properties: {
        foo: {
          type: ['string', 'null']
        }
      }
    }
  }
}

Converting OpenAPI parameters

OpenAPI parameters can be converted:

var { fromParameter } = require("@openapi-contrib/openapi-schema-to-json-schema");

var param = {
  name: "parameter name",
  in: "query",
  schema: {
    type: "string",
    format: "date",
  },
};

var convertedSchema = fromParameter(param);

console.log(convertedSchema);

The result is as follows:

{
  type: 'string',
  format: 'date',
  '$schema': 'http://json-schema.org/draft-04/schema#'
}

When a parameter has several schemas (one per MIME type) a map is returned instead.

{
  name: 'parameter name',
  in: 'query',
  content: {
    'application/javascript': {
      schema: {
        type: 'string'
      }
    },
    'text/css': {
      schema: {
        type: 'string'
      }
    }
  }
}

would be converted to:

{
  'application/javascript': {
    type: 'string',
    '$schema': 'http://json-schema.org/draft-04/schema#'
  },
  'text/css': {
    type: 'string',
    '$schema': 'http://json-schema.org/draft-04/schema#'
  }
}

Treeware

This package is Treeware. If you use it in production, then we ask that you buy the world a tree to thank us for our work. By contributing to the Treeware forest you’ll be creating employment for local families and restoring wildlife habitats.

Thanks

Copyright

Copyright 2023 the OpenAPI Contrib organization. Code released under the MIT License.