Convert Figma logo to code with AI

postmanlabs logoopenapi-to-postman

Plugin for converting OpenAPI 3.0 specs to the Postman Collection (v2) format

1,023
227
1,023
90

Top Related Projects

4,742

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

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

OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)

API Blueprint

Quick Overview

The postmanlabs/openapi-to-postman repository is a tool that converts OpenAPI specifications (formerly known as Swagger) into Postman Collections. This allows developers to easily import API definitions into Postman for testing, documentation, and collaboration purposes.

Pros

  • Simplifies the process of creating Postman Collections from OpenAPI specifications
  • Supports both OpenAPI 2.0 (Swagger) and OpenAPI 3.0 formats
  • Provides options for customizing the conversion process
  • Integrates well with Postman's ecosystem of API development tools

Cons

  • May not capture all nuances of complex OpenAPI specifications
  • Requires manual adjustments for some advanced API features
  • Limited support for certain OpenAPI extensions
  • Conversion process may occasionally produce unexpected results

Code Examples

Here are a few examples of how to use the openapi-to-postman converter:

  1. Basic conversion:
const Converter = require('openapi-to-postmanv2');

Converter.convert({ type: 'file', data: 'path/to/openapi.yaml' },
  (err, conversionResult) => {
    if (!err) {
      console.log(conversionResult.output[0].data);
    }
  }
);
  1. Conversion with options:
const options = {
  schemaFaker: false,
  requestNameSource: 'URL',
  indentCharacter: ' '
};

Converter.convert({ type: 'json', data: openapiJSON }, options,
  (err, conversionResult) => {
    if (!err) {
      console.log(conversionResult.output[0].data);
    }
  }
);
  1. Handling conversion warnings:
Converter.convert({ type: 'file', data: 'path/to/openapi.yaml' },
  (err, conversionResult) => {
    if (!err) {
      if (conversionResult.result) {
        console.log(conversionResult.output[0].data);
      }
      else {
        console.warn('Conversion completed with warnings:');
        console.warn(conversionResult.reason);
      }
    }
  }
);

Getting Started

To use openapi-to-postman in your project:

  1. Install the package:

    npm install openapi-to-postmanv2
    
  2. Import the converter in your code:

    const Converter = require('openapi-to-postmanv2');
    
  3. Use the convert method to transform your OpenAPI specification:

    Converter.convert({ type: 'file', data: 'path/to/openapi.yaml' },
      (err, conversionResult) => {
        if (!err) {
          // Handle the converted Postman Collection
          console.log(conversionResult.output[0].data);
        }
      }
    );
    

Competitor Comparisons

4,742

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

Pros of Prism

  • Offers mock server functionality out of the box
  • Supports multiple API specification formats (OpenAPI, AsyncAPI)
  • Provides a CLI tool for easy integration into workflows

Cons of Prism

  • Less focused on Postman-specific features
  • May require additional setup for complex scenarios
  • Limited customization options compared to openapi-to-postman

Code Comparison

Prism (CLI usage):

prism mock api.yaml

openapi-to-postman (Node.js usage):

const Converter = require('openapi-to-postmanv2');
Converter.convert({ type: 'file', data: 'path/to/file.yaml' },
  (err, conversionResult) => {
    // Handle conversion result
  }
);

Both tools serve different primary purposes. Prism focuses on API mocking and validation, while openapi-to-postman specializes in converting OpenAPI specifications to Postman collections. The choice between them depends on specific project requirements and workflow integration needs.

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

  • Supports a wider range of programming languages and frameworks for code generation
  • Offers more customization options for generated code
  • Has a larger community and ecosystem of plugins and extensions

Cons of swagger-codegen

  • More complex setup and configuration process
  • Steeper learning curve for advanced usage
  • May generate unnecessary boilerplate code for simpler API structures

Code Comparison

swagger-codegen:

public class PetApi {
    private final ApiClient apiClient;

    public PetApi() {
        this(Configuration.getDefaultApiClient());
    }
}

openapi-to-postman:

pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});

The code snippets demonstrate the different focus of each tool. swagger-codegen generates client-side code for API integration, while openapi-to-postman creates Postman collections for API testing and documentation.

swagger-codegen is better suited for developers who need to generate client libraries or server stubs in various programming languages. openapi-to-postman is ideal for API testing and documentation workflows within the Postman ecosystem.

Both tools serve different purposes in the API development lifecycle, with swagger-codegen offering more flexibility for code generation and openapi-to-postman providing a streamlined experience for API testing and exploration.

OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)

Pros of openapi-generator

  • Supports a wide range of programming languages and frameworks for code generation
  • Offers more comprehensive code generation capabilities, including client libraries, server stubs, and documentation
  • Provides a CLI tool for easy integration into build processes and CI/CD pipelines

Cons of openapi-generator

  • Steeper learning curve due to its extensive configuration options
  • May generate more code than necessary for simple use cases, potentially leading to bloat
  • Requires additional setup and dependencies for each target language or framework

Code Comparison

openapi-generator (Java client generation):

openapi-generator generate -i api-spec.yaml -g java -o ./generated-client

openapi-to-postman (Postman collection generation):

const result = await Converter.convert({
  type: 'string',
  data: fs.readFileSync('api-spec.yaml', 'utf8')
});

While openapi-generator focuses on generating code for various languages and frameworks, openapi-to-postman is specifically designed to create Postman collections from OpenAPI specifications. openapi-generator offers more flexibility and broader language support, but openapi-to-postman excels in simplicity for Postman-specific use cases.

API Blueprint

Pros of API Blueprint

  • More human-readable and easier to write, using Markdown syntax
  • Supports more detailed documentation with rich text formatting
  • Better for designing APIs from scratch and creating comprehensive documentation

Cons of API Blueprint

  • Less widely adopted compared to OpenAPI (formerly Swagger)
  • Limited tooling support compared to OpenAPI ecosystem
  • May require additional parsing or conversion for use with certain API tools

Code Comparison

API Blueprint:

# GET /users/{id}
+ Parameters
    + id: 1 (number, required) - User ID
+ Response 200 (application/json)
    + Attributes
        + name: John Doe (string)
        + email: john@example.com (string)

OpenAPI (used by openapi-to-postman):

/users/{id}:
  get:
    parameters:
      - name: id
        in: path
        required: true
        schema:
          type: integer
    responses:
      '200':
        content:
          application/json:
            schema:
              type: object
              properties:
                name:
                  type: string
                email:
                  type: string

While API Blueprint uses a more concise Markdown-based syntax, openapi-to-postman works with the more verbose but widely adopted OpenAPI specification. API Blueprint is better for quick, human-readable documentation, while OpenAPI offers more extensive tooling support and integration capabilities.

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

The Postman Logo

Supercharge your API workflow. Modern software is built on APIs. Postman helps you develop APIs faster.

OpenAPI 3.0, 3.1 and Swagger 2.0 to Postman Collection

Build Status

npm npm

Contents

  1. Getting Started
  2. Command Line Interface
    1. Options
    2. Usage
  3. Using the converter as a NodeJS module
    1. Convert Function
    2. Options
    3. ConversionResult
    4. Sample usage
    5. Validate function
  4. Conversion Schema


🚀 We now also support OpenAPI 3.1 and Swagger 2.0 along with OpenAPI 3.0.



💭 Getting Started

To use the converter as a Node module, you need to have a copy of the NodeJS runtime. The easiest way to do this is through npm. If you have NodeJS installed you have npm installed as well.

$ npm install openapi-to-postmanv2

If you want to use the converter in the CLI, install it globally with NPM:

$ npm i -g openapi-to-postmanv2

📖 Command Line Interface

The converter can be used as a CLI tool as well. The following command line options are available.

openapi2postmanv2 [options]

Options

  • -s <source>, --spec <source> Used to specify the OpenAPI specification (file path) which is to be converted

  • -o <destination>, --output <destination> Used to specify the destination file in which the collection is to be written

  • -p, --pretty Used to pretty print the collection object while writing to a file

  • -i, --interface-version Specifies the interface version of the converter to be used. Value can be 'v2' or 'v1'. Default is 'v2'.

  • -O, --options Used to supply options to the converter, for complete options details see here

  • -c, --options-config Used to supply options to the converter through config file, for complete options details see here

  • -t, --test Used to test the collection with an in-built sample specification

  • -v, --version Specifies the version of the converter

  • -h, --help Specifies all the options along with a few usage examples on the terminal

Usage

  • Takes a specification (spec.yaml) as an input and writes to a file (collection.json) with pretty printing and using provided options
$ openapi2postmanv2 -s spec.yaml -o collection.json -p -O folderStrategy=Tags,includeAuthInfoInExample=false
  • Takes a specification (spec.yaml) as an input and writes to a file (collection.json) with pretty printing and using provided options via config file
$ openapi2postmanv2 -s spec.yaml -o collection.json -p  -c ./examples/cli-options-config.json
  • Takes a specification (spec.yaml) as an input and writes to a file (collection.json) with pretty printing and using provided options (Also avoids any "<Error: Too many levels of nesting to fake this schema>" kind of errors present in converted collection)
$ openapi2postmanv2 -s spec.yaml -o collection.json -p -O folderStrategy=Tags,requestParametersResolution=Example,optimizeConversion=false,stackLimit=50
  • Testing the converter
$ openapi2postmanv2 --test

🛠 Using the converter as a NodeJS module

In order to use the convert in your node application, you need to import the package using require.

var Converter = require('openapi-to-postmanv2')

The converter provides the following functions:

Convert

The convert function takes in your OpenAPI 3.0, 3.1 and Swagger 2.0 specification ( YAML / JSON ) and converts it to a Postman collection.

Signature: convert (data, options, callback);

data:

{ type: 'file', data: 'filepath' }
OR
{ type: 'string', data: '<entire OpenAPI string - JSON or YAML>' }
OR
{ type: 'json', data: OpenAPI-JS-object }

options:

{
  schemaFaker: true,
  requestNameSource: 'fallback',
  indentCharacter: ' '
}
/*
All three properties are optional. Check the options section below for possible values for each option.
*/

Note: All possible values of options and their usage can be found over here: OPTIONS.md

callback:

function (err, result) {
  /*
  result = {
    result: true,
    output: [
      {
        type: 'collection',
        data: {..collection object..}
      }
    ]
  }
  */
}

Options

Check out complete list of options and their usage at OPTIONS.md

ConversionResult

  • result - Flag responsible for providing a status whether the conversion was successful or not.

  • reason - Provides the reason for an unsuccessful conversion, defined only if result if false.

  • output - Contains an array of Postman objects, each one with a type and data. The only type currently supported is collection.

Sample Usage

const fs = require('fs'),
  Converter = require('openapi-to-postmanv2'),
  openapiData = fs.readFileSync('sample-spec.yaml', {encoding: 'UTF8'});

Converter.convert({ type: 'string', data: openapiData },
  {}, (err, conversionResult) => {
    if (!conversionResult.result) {
      console.log('Could not convert', conversionResult.reason);
    }
    else {
      console.log('The collection object is: ', conversionResult.output[0].data);
    }
  }
);

Validate Function

The validate function is meant to ensure that the data that is being passed to the convert function is a valid JSON object or a valid (YAML/JSON) string.

The validate function is synchronous and returns a status object which conforms to the following schema

Validation object schema

{
  type: 'object',
  properties: {
    result: { type: 'boolean'},
    reason: { type: 'string' }
  },
  required: ['result']
}
Validation object explanation
  • result - true if the data looks like OpenAPI and can be passed to the convert function

  • reason - Provides a reason for an unsuccessful validation of the specification

🧭 Conversion Schema

postmanopenapirelated options
collectionNameinfo.title-
descriptioninfo.description + info.contact-
collectionVariablesserver.variables + pathVariables-
folderNamepaths.path / tags.namefolderStrategy
requestNameoperationItem(method).summary / operationItem(method).operationId / urlrequestNameSource
request.methodpath.method-
request.headersparameter (in = header)-
request.bodyoperationItem(method).requestBodyrequestParametersResolution, exampleParametersResolution
request.url.rawserver.url (path level server >> openapi server) + path-
request.url.variablesparameter (in = path)-
request.url.paramsparameter (in = query)-
api_key in (query or header)components.securitySchemes.api_keyincludeAuthInfoInExample