Convert Figma logo to code with AI

APIDevTools logoswagger-parser

Swagger 2.0 and OpenAPI 3.0 parser/validator

1,088
154
1,088
74

Top Related Projects

The OpenAPI Specification Repository

Examples and server integrations for generating the Swagger API Specification, which enables easy access to your REST API

swagger-codegen contains a template-driven engine to generate documentation, API clients and server stubs in different languages by parsing your OpenAPI / Swagger definition.

23,260

📘 OpenAPI/Swagger-generated API Reference Documentation

4,216

Turn any OpenAPI2/3 and Postman Collection file into an API server with mocking, transformations and validations.

Swagger 2.0 implementation for go

Quick Overview

Swagger Parser is a JavaScript library that parses, validates, and dereferences Swagger and OpenAPI definitions. It supports OpenAPI 3.0 and 2.0 (formerly known as Swagger) in JSON and YAML formats, providing a unified interface for working with API specifications.

Pros

  • Supports both OpenAPI 3.0 and 2.0 specifications
  • Handles JSON and YAML formats seamlessly
  • Provides validation and dereferencing capabilities
  • Offers both synchronous and asynchronous parsing methods

Cons

  • Limited to JavaScript/Node.js environments
  • May have performance issues with very large API specifications
  • Requires additional dependencies for full functionality
  • Documentation could be more comprehensive for advanced use cases

Code Examples

  1. Parsing an OpenAPI specification:
const SwaggerParser = require("@apidevtools/swagger-parser");

SwaggerParser.parse("path/to/api.yaml")
  .then(api => console.log("API name: %s, Version: %s", api.info.title, api.info.version))
  .catch(err => console.error(err));
  1. Validating an OpenAPI specification:
const SwaggerParser = require("@apidevtools/swagger-parser");

SwaggerParser.validate("path/to/api.json")
  .then(api => console.log("API is valid"))
  .catch(err => console.error("API is invalid: " + err.message));
  1. Dereferencing an OpenAPI specification:
const SwaggerParser = require("@apidevtools/swagger-parser");

SwaggerParser.dereference("path/to/api.yaml")
  .then(api => console.log("Dereferenced API:", JSON.stringify(api, null, 2)))
  .catch(err => console.error(err));

Getting Started

To use Swagger Parser in your project, follow these steps:

  1. Install the package:

    npm install @apidevtools/swagger-parser
    
  2. Import and use the library in your code:

    const SwaggerParser = require("@apidevtools/swagger-parser");
    
    SwaggerParser.validate("https://api.example.com/openapi.json")
      .then(api => console.log("API is valid"))
      .catch(err => console.error("API is invalid"));
    

This example validates an OpenAPI specification from a URL. You can also use local file paths or JavaScript objects as input.

Competitor Comparisons

The OpenAPI Specification Repository

Pros of OpenAPI-Specification

  • Official specification repository, providing the authoritative source for OpenAPI standards
  • Extensive documentation and examples for implementing OpenAPI in various scenarios
  • Active community involvement and regular updates to the specification

Cons of OpenAPI-Specification

  • Focuses on the specification itself, not providing parsing or validation tools
  • May require additional tools or libraries for practical implementation in projects

Code Comparison

OpenAPI-Specification (YAML example):

openapi: 3.0.0
info:
  title: Sample API
  version: 1.0.0
paths:
  /users:
    get:
      summary: Returns a list of users

swagger-parser (JavaScript example):

const SwaggerParser = require("@apidevtools/swagger-parser");

SwaggerParser.validate("api.yaml", (err, api) => {
  if (err) {
    console.error(err);
  } else {
    console.log("API name: %s, Version: %s", api.info.title, api.info.version);
  }
});

Summary

OpenAPI-Specification serves as the definitive source for OpenAPI standards, offering comprehensive documentation and community support. However, it doesn't provide tools for parsing or validating OpenAPI documents. In contrast, swagger-parser offers practical utilities for working with OpenAPI files, including parsing and validation capabilities, making it more suitable for direct implementation in projects.

Examples and server integrations for generating the Swagger API Specification, which enables easy access to your REST API

Pros of swagger-core

  • More comprehensive toolset for working with OpenAPI specifications
  • Offers annotation-based API documentation generation
  • Provides deeper integration with Java ecosystem and frameworks

Cons of swagger-core

  • Heavier and more complex, potentially overkill for simple parsing needs
  • Primarily focused on Java, limiting its use in other programming languages
  • Steeper learning curve due to its extensive feature set

Code Comparison

swagger-core (Java):

@Path("/users")
@Api(value = "/users")
public class UserResource {
    @GET
    @ApiOperation(value = "Get all users")
    public Response getUsers() {
        // Implementation
    }
}

swagger-parser (JavaScript):

const SwaggerParser = require("@apidevtools/swagger-parser");

SwaggerParser.validate("api.yaml", (err, api) => {
  if (err) {
    console.error(err);
  } else {
    console.log("API name: %s, Version: %s", api.info.title, api.info.version);
  }
});

Key Differences

  • swagger-core is more focused on Java development and integration with Java frameworks
  • swagger-parser is language-agnostic and primarily aimed at parsing and validating OpenAPI documents
  • swagger-core offers more features for API development, while swagger-parser specializes in parsing and validation
  • swagger-parser is lighter and easier to use for simple parsing tasks
  • swagger-core provides more comprehensive tools for generating API documentation from code

swagger-codegen contains a template-driven engine to generate documentation, API clients and server stubs in different languages by parsing your OpenAPI / Swagger definition.

Pros of swagger-codegen

  • Generates client SDKs, server stubs, and documentation for multiple languages and frameworks
  • Supports customization of generated code through templates and configuration options
  • Offers a wider range of features for API development lifecycle

Cons of swagger-codegen

  • More complex to set up and use compared to swagger-parser
  • Larger project size and longer build times
  • May generate unnecessary code for simpler API projects

Code Comparison

swagger-parser:

const SwaggerParser = require("@apidevtools/swagger-parser");

SwaggerParser.validate("api.yaml", (err, api) => {
  if (err) {
    console.error(err);
  } else {
    console.log("API name: %s, Version: %s", api.info.title, api.info.version);
  }
});

swagger-codegen:

public class SwaggerCodegen {
    public static void main(String[] args) {
        CodegenConfigurator configurator = new CodegenConfigurator()
            .setInputSpec("api.yaml")
            .setLang("java")
            .setOutputDir("generated-code");
        DefaultGenerator generator = new DefaultGenerator();
        generator.opts(configurator.toClientOptInput()).generate();
    }
}

Summary

swagger-parser is a lightweight tool focused on parsing and validating OpenAPI/Swagger definitions. It's ideal for simple API validation tasks and quick integrations. swagger-codegen, on the other hand, is a more comprehensive tool that generates client SDKs, server stubs, and documentation for various languages and frameworks. While swagger-codegen offers more features and customization options, it comes with increased complexity and longer build times. The choice between the two depends on the specific needs of your API project.

23,260

📘 OpenAPI/Swagger-generated API Reference Documentation

Pros of Redoc

  • Offers a visually appealing and interactive API documentation interface
  • Supports theming and customization options for better branding
  • Provides a responsive design for mobile and desktop viewing

Cons of Redoc

  • Focused primarily on documentation rendering, not parsing or validation
  • May require additional setup for complex API structures
  • Limited to OpenAPI/Swagger specifications

Code Comparison

Redoc (HTML usage):

<script src="https://cdn.redoc.ly/redoc/latest/bundles/redoc.standalone.js"></script>
<redoc spec-url="https://api.example.com/openapi.json"></redoc>

Swagger Parser (JavaScript usage):

const SwaggerParser = require("@apidevtools/swagger-parser");

SwaggerParser.validate("https://api.example.com/openapi.json", (err, api) => {
  if (err) console.error(err);
  else console.log("API name: %s, Version: %s", api.info.title, api.info.version);
});

Key Differences

Redoc is primarily a documentation rendering tool, offering a polished and interactive interface for API consumers. It excels in presenting API information in a user-friendly manner.

Swagger Parser, on the other hand, focuses on parsing, validating, and working with OpenAPI/Swagger specifications programmatically. It's more suited for developers who need to manipulate or validate API definitions in their applications.

While both tools work with OpenAPI/Swagger specifications, they serve different purposes in the API development lifecycle. Redoc is ideal for creating beautiful API documentation, while Swagger Parser is better for backend processing and validation of API definitions.

4,216

Turn any OpenAPI2/3 and Postman Collection file into an API server with mocking, transformations and validations.

Pros of Prism

  • Offers API mocking and validation capabilities, providing a more comprehensive toolset for API development
  • Supports multiple API specification formats, including OpenAPI, AsyncAPI, and JSON Schema
  • Provides a CLI interface for easy integration into development workflows

Cons of Prism

  • May have a steeper learning curve due to its broader feature set
  • Potentially slower performance for large API specifications compared to Swagger Parser
  • Less focused on parsing and validation, as it covers a wider range of functionalities

Code Comparison

Swagger Parser:

const SwaggerParser = require("@apidevtools/swagger-parser");

SwaggerParser.validate("api.yaml", (err, api) => {
  if (err) {
    console.error(err);
  } else {
    console.log("API name: %s, Version: %s", api.info.title, api.info.version);
  }
});

Prism:

const { Prism } = require("@stoplight/prism-core");
const { createHttpHandlerFromSpec } = require("@stoplight/prism-http");

const prism = new Prism({
  components: { http: createHttpHandlerFromSpec("api.yaml") },
});
prism.server.listen(3000);

Both tools serve different primary purposes. Swagger Parser focuses on parsing and validating OpenAPI specifications, while Prism offers a broader set of features for API mocking and testing. The choice between them depends on the specific needs of your API development workflow.

Swagger 2.0 implementation for go

Pros of go-swagger

  • Native Go implementation, offering better performance and integration for Go projects
  • Provides a complete toolkit for working with Swagger/OpenAPI, including code generation
  • Supports both Swagger 2.0 and OpenAPI 3.0 specifications

Cons of go-swagger

  • Limited to Go language ecosystem, unlike swagger-parser's language-agnostic approach
  • Steeper learning curve due to its comprehensive feature set
  • May be overkill for simple parsing tasks

Code Comparison

swagger-parser (JavaScript):

const SwaggerParser = require("@apidevtools/swagger-parser");

SwaggerParser.validate("api.yaml", (err, api) => {
  if (err) {
    console.error(err);
  } else {
    console.log("API name: %s, Version: %s", api.info.title, api.info.version);
  }
});

go-swagger (Go):

import "github.com/go-swagger/go-swagger/cmd/swagger"

func main() {
    swagger.Main(os.Args[1:])
}

Key Differences

  • swagger-parser focuses on parsing and validating Swagger/OpenAPI documents
  • go-swagger offers a broader set of tools, including server and client code generation
  • swagger-parser is more suitable for multi-language projects, while go-swagger is Go-specific
  • go-swagger provides a CLI tool, making it easier to integrate into build processes

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Swagger 2.0 and OpenAPI 3.0 parser/validator

Build Status Coverage Status Tested on APIs.guru

npm Dependencies License Buy us a tree

OS and Browser Compatibility

Online Demo

Features

  • Parses Swagger specs in JSON or YAML format
  • Validates against the Swagger 2.0 schema or OpenAPI 3.0 Schema
  • Resolves all $ref pointers, including external files and URLs
  • Can bundle all your Swagger files into a single file that only has internal $ref pointers
  • Can dereference all $ref pointers, giving you a normal JavaScript object that's easy to work with
  • Tested in Node.js and all modern web browsers on Mac, Windows, and Linux
  • Tested on over 1,500 real-world APIs from Google, Microsoft, Facebook, Spotify, etc.
  • Supports circular references, nested references, back-references, and cross-references
  • Maintains object reference equality — $ref pointers to the same value always resolve to the same object instance

Related Projects

Example

SwaggerParser.validate(myAPI, (err, api) => {
  if (err) {
    console.error(err);
  }
  else {
    console.log("API name: %s, Version: %s", api.info.title, api.info.version);
  }
});

Or use async/await or Promise syntax instead. The following example is the same as above:

try {
  let api = await SwaggerParser.validate(myAPI);
  console.log("API name: %s, Version: %s", api.info.title, api.info.version);
}
catch(err) {
  console.error(err);
}

For more detailed examples, please see the API Documentation

Installation

Install using npm:

npm install @apidevtools/swagger-parser

Usage

When using Swagger Parser in Node.js apps, you'll probably want to use CommonJS syntax:

const SwaggerParser = require("@apidevtools/swagger-parser");

When using a transpiler such as Babel or TypeScript, or a bundler such as Webpack or Rollup, you can use ECMAScript modules syntax instead:

import * as SwaggerParser from '@apidevtools/swagger-parser';

Browser support

Swagger Parser supports recent versions of every major web browser. Older browsers may require Babel and/or polyfills.

To use Swagger Parser in a browser, you'll need to use a bundling tool such as Webpack, Rollup, Parcel, or Browserify. Some bundlers may require a bit of configuration, such as setting browser: true in rollup-plugin-resolve.

API Documentation

Full API documentation is available right here

Contributing

I welcome any contributions, enhancements, and bug-fixes. Open an issue on GitHub and submit a pull request.

Building/Testing

To build/test the project locally on your computer:

  1. Clone this repo
    git clone https://github.com/APIDevTools/swagger-parser.git

  2. Install dependencies
    npm install

  3. Run the build script
    npm run build

  4. Run the tests
    npm test

  5. Check the code coverage
    npm run coverage

License

Swagger Parser is 100% free and open-source, under the MIT license. Use it however you want.

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.

Big Thanks To

Thanks to these awesome companies for their support of Open Source developers ❤

GitHub NPM Coveralls

NPM DownloadsLast 30 Days