Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 43 additions & 51 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# Penify Open API Code Gen

# Open API Code Gen

Openapi-code-gen is a JavaScript library designed to convert OpenAPI schemas into various code examples. This tool simplifies the process of generating client libraries in different programming languages based on your API documentation.
`penify-oapi-codegen` is a JavaScript library designed to convert OpenAPI schemas into various code examples. This tool simplifies the process of generating client libraries in different programming languages based on your API documentation.

## Features

Expand All @@ -10,7 +9,7 @@ Openapi-code-gen is a JavaScript library designed to convert OpenAPI schemas int

## Prerequisites

Before installing `openapi-code-gen`, ensure you have the following installed:
Before installing `penify-oapi-codegen`, ensure you have the following installed:

- [Node.js](https://nodejs.org/) (version 12 or higher)
- npm (Node package manager)
Expand All @@ -23,82 +22,75 @@ npm install -g openapi-to-postmanv2

## Installation

To install `openapi-code-gen`, run the following command:
To install `penify-oapi-codegen`, run the following command:

```bash
npm install openapi-code-gen
npm install penify-oapi-codegen
```

## Usage

Once installed, you can use `openapi-code-gen` from the command line to generate code examples from your OpenAPI schemas.
Once installed, you can use `penify-oapi-codegen` from the command line to generate code examples from your OpenAPI schemas.

### Generate Code Examples

```bash
openapi-code-gen generate -i path/to/your/openapi/schema.yaml -l language -v variant -o path/to/output/code_example
penify-oapi-codegen -i path/to/your/openapi/schema.json -l language -v variant -o path/to/output/schema_with_code.json
```

### Options

- `generate`: Generates code examples from an OpenAPI schema.
- `-i, --input <path>`: Path to the OpenAPI schema file (required).
- `-l, --language <language>`: Programming language for the code example (required).
- `-v, --variant <variant>`: Variant of the code generator for the specified language (required).
- `-o, --output <path>`: Path to the output code example file (required).
- `-s, --source <path>`: Path to the OpenAPI schema file (required).
- `-l, --language <language>`: Programming language for the code example (optional).
- `-v, --variant <variant>`: Variant of the code generator for the specified language (optional).
- `-o, --output <path>`: Path to the output code example file (optional).
- `-s,`: To show list of supported languages

## Supported Code Generators

The tool supports generating code examples for the following languages and variants:

| Language | Variant |
|---------------|---------------|
| C | libcurl |
| C# | HttpClient |
| C# | RestSharp |
| cURL | cURL |
| Dart | http |
| Go | Native |
| HTTP | HTTP |
| Java | OkHttp |
| Java | Unirest |
| JavaScript | Fetch |
| JavaScript | jQuery |
| JavaScript | XHR |
| Kotlin | OkHttp |
| NodeJs | Axios |
| NodeJs | Native |
| NodeJs | Request |
| NodeJs | Unirest |
| Objective-C | NSURLSession |
| OCaml | Cohttp |
| PHP | cURL |
| PHP | Guzzle |
| PHP | pecl_http |
| PHP | HTTP_Request2 |
| PowerShell | RestMethod |
| Python | http.client |
| Python | Requests |
| R | httr |
| R | RCurl |
| Rust | Reqwest |
| Ruby | Net:HTTP |
| Shell | Httpie |
| Shell | wget |
| Swift | URLSession |
| Language | Variant |
|--------------- |----------------|
| csharp | RestSharp |
| curl | cURL |
| go | Native |
| http | HTTP |
| java | OkHttp |
| java | Unirest |
| javascript | Fetch |
| javascript | jQuery |
| javascript | XHR |
| c | libcurl |
| nodejs | Axios |
| nodejs | Native |
| nodejs | Request |
| nodejs | Unirest |
| objective-c | NSURLSession |
| ocaml | Cohttp |
| php | cURL |
| php | HTTP_Request2 |
| php | pecl_http |
| powershell | RestMethod |
| python | http.client |
| python | Requests |
| ruby | Net::HTTP |
| shell | Httpie |
| shell | wget |
| swift | URLSession |

## Examples

### Example 1: Generate Python Requests Code Example

```bash
openapi-code-gen generate -i ./schemas/api.yaml -l Python -v Requests -o ./examples/python_requests_example.py
penify-oapi-codegen -s ./schemas/api.json -l python -v Requests -o ./examples/schema_python_requests_example.json
```

### Example 2: Generate JavaScript Fetch Code Example

```bash
openapi-code-gen generate -i ./schemas/api.yaml -l JavaScript -v Fetch -o ./examples/js_fetch_example.js
penify-oapi-codegen -s ./schemas/api.json -l javascript -v Fetch -o ./examples/schema_js_fetch_example.json
```

## Contributing
Expand All @@ -111,7 +103,7 @@ This project is licensed under the ISC License.

## Author

[Your Name]
sumansaurabh

---

Expand Down
7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "penify-oapi-codegen",
"version": "1.0.0",
"version": "1.0.1",
"description": "A JavaScript library to convert OpenAPI schema to Postman collection and generate sample code.",
"main": "src/index.js",
"scripts": {
Expand All @@ -10,21 +10,22 @@
"test": "jest"
},
"bin": {
"openapi-code-gen": "src/index.js"
"penify-oapi-codegen": "src/index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"openapi-to-postmanv2": "4.21.0",
"postman-code-generators": "1.10.1",
"postman-code-generators": "^1.0.2",
"postman-collection": "^4.4.0"
},
"devDependencies": {
"@eslint/js": "^9.4.0",
"eslint": "^9.4.0",
"globals": "^15.4.0",
"jest": "^29.7.0",
"js-yaml": "^4.1.0",
"uuid": "^9.0.1"
},
"peerDependencies": {
Expand Down
30 changes: 25 additions & 5 deletions src/OpenAPIHelper.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,21 @@ const fs = require('fs');
const { Collection, Item } = require('postman-collection');
const codegen = require('postman-code-generators');
const { execSync } = require('child_process');
const yaml = require('js-yaml');
const path = require('path');

class OpenAPIHelper {
static convertOpenAPIToPostman(openAPIPath, postmanOutputPath) {
execSync(`openapi2postmanv2 -s ${openAPIPath} -o ${postmanOutputPath}`, { stdio: 'inherit' });
}

static getSupportedLanguagesAndVariants() {
const languages = codegen.getLanguageList();
const supportedLanguages = [];
languages.forEach(lang => lang.variants.forEach(vari => supportedLanguages.push({ language: lang.key, variant: vari.key }))) ;
return supportedLanguages;
}

static generateSampleCode(postmanCollectionPath, language = null, variant = null) {
const collection = JSON.parse(fs.readFileSync(postmanCollectionPath).toString());

Expand Down Expand Up @@ -37,7 +46,7 @@ class OpenAPIHelper {
console.error(error);
} else {
const fileName = `${operationId}_${language}_${variant}.pm`;
fs.writeFileSync(`sample_code/${fileName}`, snippet);
fs.writeFileSync(`/tmp/sample_code/${fileName}`, snippet);
}
});
};
Expand All @@ -48,7 +57,6 @@ class OpenAPIHelper {
const method = item.request.method.toLowerCase(); // eg: "get"
const operationId = `${name.join('_')}_${url.join('_')}_${method}`;
return operationId;

}

function processItems(items) {
Expand All @@ -71,10 +79,18 @@ class OpenAPIHelper {
}

static addSampleCodeToOpenAPI(openAPIPath, outputAPIPath) {
const openapiSchema = JSON.parse(fs.readFileSync(openAPIPath).toString());
let openapiSchema;
const ext = path.extname(openAPIPath);

if (ext === '.yaml' || ext === '.yml') {
openapiSchema = yaml.load(fs.readFileSync(openAPIPath, 'utf8'));
} else {
openapiSchema = JSON.parse(fs.readFileSync(openAPIPath).toString());
}

const sampleCode = {};

fs.readdirSync('sample_code').forEach(file => {
fs.readdirSync('/tmp/sample_code').forEach(file => {
const code = fs.readFileSync(`/tmp/sample_code/${file}`).toString();
const [operationId, lang, vari] = file.replace('.pm', '').split('~');
if (!sampleCode[operationId]) {
Expand All @@ -98,7 +114,11 @@ class OpenAPIHelper {
});
});

fs.writeFileSync(outputAPIPath, JSON.stringify(openapiSchema, null, 2));
if (ext === '.yaml' || ext === '.yml') {
fs.writeFileSync(outputAPIPath, yaml.dump(openapiSchema));
} else {
fs.writeFileSync(outputAPIPath, JSON.stringify(openapiSchema, null, 2));
}
}
}

Expand Down
36 changes: 26 additions & 10 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,11 @@ const { hideBin } = require('yargs/helpers');

// Parse command-line arguments
const argv = yargs(hideBin(process.argv))
.usage('Usage: penify-oapi-codegen -s <source> -l <language> -v <variant> -o <output>')
.option('s', {
alias: 'source',
describe: 'Path to the OpenAPI JSON file',
type: 'string',
demandOption: true
.usage('Usage: penify-oapi-codegen -i <input> -l <language> -v <variant> -o <output> \n penify-oapi-codegen -s')
.option('i', {
alias: 'input',
describe: 'Path to the OpenAPI JSON or YAML file',
type: 'string'
})
.option('l', {
alias: 'language',
Expand All @@ -30,21 +29,38 @@ const argv = yargs(hideBin(process.argv))
describe: 'Output file path (optional)',
type: 'string'
})
.option('s', {
alias: 'supported-languages',
describe: 'Get the list of supported languages',
type: 'boolean'
})
.help()
.argv;

const openAPIPath = argv.s;
const openAPIPath = argv.i;
const language = argv.l || null;
const variant = argv.v || null;
const outputAPIPath = argv.o || path.resolve(`${path.basename(openAPIPath)}_with_code.json`);
const showSupportedLanguages = argv.s || null;

if (showSupportedLanguages) {
const supportedLanguages = OpenAPIHelper.getSupportedLanguagesAndVariants();
console.log('| Language | Variant |');
console.log('|----------------|----------------|');
supportedLanguages.forEach(item => {
console.log(`| ${item.language.padEnd(14)} | ${item.variant.padEnd(14)} |`);
});
process.exit(0);
}


const outputAPIPath = argv.o || path.resolve(`${path.basename(openAPIPath, path.extname(openAPIPath))}_with_code.json`);

if (!openAPIPath) {
console.error('Please provide the path to the OpenAPI JSON file.');
console.error('Please provide the path to the OpenAPI file.');
process.exit(1);
}

const resolvedOpenAPIPath = path.resolve(openAPIPath);
const file_name = path.basename(resolvedOpenAPIPath);
const guid = uuidv4();

const postmanOutputPath = path.resolve(`/tmp/openapi_schema_postman_${guid}.json`);
Expand Down