4

I've generated my client typescript/angular2 language using https://github.com/swagger-api/swagger-codegen via a Java Command.

But i would like to generate my client typescript/angular2 using an npm command not a java command.

Example :

  npm install swagger-codegen -g
  swagger-codegen generate -i http://petstore.swagger.io/v2/swagger.json -l
  typescript-angular2 -o c:\temp\angular2_api_client

I'am using windows 8.1 OS. I didn't find swagger-codegen command to install with npm.

mahdi kallel
  • 453
  • 1
  • 6
  • 15

2 Answers2

2

I've found a solution to generate a client API for Angular 2 TypeScript without java command but using node command.

Example node script to generate typescript angular client from swagger.yaml. Note that we use http. Request cannot verify the first certificate if using https (at the time of writing this)

This is app.js

var fs = require('fs');
var path = require('path');
var jsYaml = require('js-yaml');
var request = require('request');
var unzip = require('unzip2');

var codeGenEndpoint = 'http://generator.swagger.io/api/gen/clients';
var language = 'typescript-angular2';

fs.readFile(path.resolve('swagger.yaml'), 'utf8', function (error, yaml) {
    if (error) {
        throw error;
    }

    var swaggerObj = jsYaml.load(yaml);

    var postBody = {
        spec: swaggerObj,
        options: {
            modelPropertyNaming: 'camelCase',
            apiPackage: 'api.clients.settings',
            modelPackage: 'api.clients.settings'
        }
    };

    request.post({
        url: codeGenEndpoint + '/' + language,
        body: JSON.stringify(postBody),
        headers: {
            'Content-Type': 'application/json'
        }
    }, function(error, response, body){
        if (error) {
            throw error;
        }

        if (response.statusCode !== 200) {
            throw new Error('Response code was not 200. ' + body)
        }

        var responseObj = JSON.parse(body);

        request({
            url: responseObj.link,
            encoding: null
        }).pipe(unzip.Extract({ path: 'src/client/js/codegen/settingsApi'}));
    });
});

I just set variable language to 'typescript-angular2'. After that node app.js

For the list of available client languages just visit http://generator.swagger.io/api/gen/clients

And for more details: https://github.com/swagger-api/swagger-codegen/wiki/FAQ section Generator Service

YakovL
  • 7,557
  • 12
  • 62
  • 102
mahdi kallel
  • 453
  • 1
  • 6
  • 15
  • 1
    Thanks for this! If you are on Node 12 or higher, use `node-unzip-2` instead of `unzip2`. Also change the protocol on the codegen endpoint to `https` and use `https://generator.swagger.io/api/gen/clients` to get a list of compatible clients. – Kunal Sep 07 '20 at 15:05
1

Are you looking for something like this?

npm install @openapitools/openapi-generator-cli -g
user3007799
  • 137
  • 1
  • 8