Code Monkey home page Code Monkey logo

generator-jhipster-swagger-cli's Introduction

Deprecation warning: from JHipster 6.3.0, this module has been integrated in the main generator and shall not be used anymore.

generator-jhipster-swagger-cli

NPM version Build Status Dependency Status

JHipster module to generate client code from an OpenAPI/Swagger definition

Introduction

This is a JHipster module, that is meant to be used in a JHipster application.

This module generates client code using Spring-Cloud FeignClients in your JHipster app from an OpenAPI/Swagger definition.

The generated FeignClient can be used in both Monolithic and Micro-service applications.

This module works for JHipster v5+ apps. For older JHipster version, use version 2.x of this module (branch v2.x-JHipster2-3-4)

This module works with both Swagger v2 and OpenAPI v3 definitions.

Prerequisites

As this is a JHipster module, we expect you have JHipster and its related tools already installed:

Installation

To install this module:

npm install -g generator-jhipster-swagger-cli

To update this module:

npm update -g generator-jhipster-swagger-cli

Usage

Run:

yo jhipster-swagger-cli

then answer the questions. You have the possibility to store a client configuration for future regeneration (eg. if there is an API update). If you do so, next time you launch the module, you will have the choice to generate a new client or to reuse one or several stored configurations.

Use the generated back-end Spring-Cloud FeignClient code

Client configuration

You can configure the generated FeignClients directly from the application.yml. RequestInterceptor beans are generated from the OpenAPI securitySchemes and are only activated if relevant properties are set. If the OpenAPI spec doesn't contain the securitySchemes, then you will need to configure the clients by yourself (see spring-cloud doc for details.)

Configuring basic auth

The basic auth RequestInterceptor is activated if <clientName>.security.<securityName>.username is set.

petstore:
    security:
        basicAuth:
            username: admin
            password: admin

Configuring API key auth

The API key RequestInterceptor is activated if <clientName>.security.<securityName>.key is set.

petstore:
    security:
        apiKey:
            key: 12345

Configuring OAuth2

The OAuth2 RequestInterceptor is activated if <clientName>.security.<securityName>.key is set. For details on configuring OAuth2, see the spring-security-oauth2 doc.

petstore:
    security:
        passwordOauth:
            client-id: myClientId
            client-secret: myClientSecret
            username: myUsername
            password: myPassword
            scopes:
            - read
            - write

Configuring the remote URL

The remote URL will default to the one from the OpenAPI spec but can be changed with the <clientName>.url property.

petstore:
    url: http://petstore-uat.swagger.io/v2

Use Ribbon (w/wo Eureka)

You need to add spring-cloud-starter-ribbon to your pom.xml if needed. Note that it seems to cause an issue with form-login on monoliths so it is not done by this module. Then set <cliName>.url to blank.

petstore:
    url:
    ribbon:
        listOfServers: petstore1.swagger.io,petstore2.swagger.io

Advanced configuration

If the generated clients don't fit your needs because you want to use Hystrix fallbacks, change the Ribbon context path or use different Feign client configuration, then simply create your own FeignClient beans extending the generated xxxApi classes.

Calling API methods

For instance if you generated the petstore API, you can call the addPet method like this:

@Inject
private PetApiClient petApiClient;
...
Pet myPet = new Pet();
petApiClient.addPet(myPet);

License

Apache-2.0 © [Christophe Bornet]

generator-jhipster-swagger-cli's People

Contributors

cbornet avatar pierrebesson avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

generator-jhipster-swagger-cli's Issues

Once a front-end rest client has been added to the app, the home page does not load

I tried several times and keep encountering this issue. I'm using the latest master so that may be the reason.
I simply generated a new jhipster app and a swagger-cli client on the petstore. I'm using jhipster-swagger-cli version 0.4.0.

{
  "generator-jhipster": {
    "jhipsterVersion": "2.27.0",
    "baseName": "jhip",
    "packageName": "com.ippon.pierre",
    "packageFolder": "com/ippon/pierre",
    "authenticationType": "session",
    "hibernateCache": "ehcache",
    "clusteredHttpSession": "no",
    "websocket": "no",
    "databaseType": "sql",
    "devDatabaseType": "h2Disk",
    "prodDatabaseType": "mysql",
    "searchEngine": "no",
    "buildTool": "maven",
    "enableSocialSignIn": false,
    "rememberMeKey": "5100327d57c88bb37b25f6e3e84483337eb7d0c2",
    "useSass": false,
    "enableTranslation": true,
    "applicationType": "monolith",
    "testFrameworks": [
      "gatling"
    ]
  },
  "generator-jhipster-swagger-cli": {
    "apis": {
      "petstore": {
        "spec": "http://petstore.swagger.io/v2/swagger.json",
        "cliTypes": [
          "front"
        ]
      }
    }
  }
}

JWT auth not supported in backend?

Sorry if I am misled, but could it be that JWT auth (the jHipster default) is not yet supported?
I found nothing about it so far, despite the test in travis subdir (which imho says "authentication failed" in last run of tests in travis logs).

In a microservice context discover the available swagger-docs automatically using Eureka or Zuul

As the jhipster microservice version is getting merged to the main generator we could provide this as an option.
However I don't know if we should discover the services directly on the Eureka registry or through a Zuul route on the gateway. The former might be good enough for a Feign client (as it need only the service ID to call it) and the latter for an Angular client (as it need to know the route to call the right REST endpoint).
What do you think @jdubois ?

Once the jhiregistry is started we can get the list of available registered microservices. Usually the registry is located on localhost:8761.

GET http://localhost:8761/eureka/apps

<?xml version="1.0" encoding="UTF-8"?>
<applications>
   <versions__delta>1</versions__delta>
   <apps__hashcode>UP_1_</apps__hashcode>
   <application>
      <name>APP1</name>
      <instance>
         <instanceId>app1:3bcde735f84db35caa06fd101b8d1cb0</instanceId>
         <hostName>192.168.43.8</hostName>
         <app>APP1</app>
         <ipAddr>192.168.43.8</ipAddr>
         <status>UP</status>
         <overriddenstatus>UNKNOWN</overriddenstatus>
         <port enabled="true">8090</port>
         <securePort enabled="false">443</securePort>
         <countryId>1</countryId>
         <dataCenterInfo class="com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo">
            <name>MyOwn</name>
         </dataCenterInfo>
         <leaseInfo>
            <renewalIntervalInSecs>30</renewalIntervalInSecs>
            <durationInSecs>90</durationInSecs>
            <registrationTimestamp>1454601030889</registrationTimestamp>
            <lastRenewalTimestamp>1454601451272</lastRenewalTimestamp>
            <evictionTimestamp>0</evictionTimestamp>
            <serviceUpTimestamp>1454601030889</serviceUpTimestamp>
         </leaseInfo>
         <metadata class="java.util.Collections$EmptyMap" />
         <homePageUrl>http://192.168.43.8:8090/</homePageUrl>
         <statusPageUrl>http://192.168.43.8:8080/info</statusPageUrl>
         <healthCheckUrl>http://192.168.43.8:8080/health</healthCheckUrl>
         <vipAddress>app1</vipAddress>
         <isCoordinatingDiscoveryServer>false</isCoordinatingDiscoveryServer>
         <lastUpdatedTimestamp>1454601030890</lastUpdatedTimestamp>
         <lastDirtyTimestamp>1454601030715</lastDirtyTimestamp>
         <actionType>ADDED</actionType>
      </instance>
   </application>
</applications>

From there it's easy to get the swagger-docs at http://192.168.43.8:8090/v2/api-docs

Or on the Zuul Gateway (on localhost:8080):

GET http://localhost:8080/routes

{"/app1/**":"app1"}

We can get the swagger-docs for app1 here : http://localhost:8080/app1/v2/api-docs

Finally, maybe after getting the list of all available endpoints on all microservices then one of the choice we could offer is to cherry-pick the ones we want to consume in our service and generate their rest client code.

Update for JH 3.7.1 AuthorizedFeignClient compatibility

JH 3.7.1 added Spring Cloud Feign Client integration so it would be nice if this generator could support that. It's not that difficult to do manually so hopefully not too difficult to add support in this generator.

Here's an example.

jhipster gateway with jhipster uaa microservice.

URL = http://localhost:8080/uaa/v2/api-docs
ApiClient Name = uaa

backend-client files should be generated like so

java/com/test/client/uaa/UaaApiClient.java
java/com/test/client/uaa/api/UaaApi.java
java/com/test/client/uaa/model/KeyAndPasswordVM.java
java/com/test/client/uaa/model/ManagedUserVM.java
java/com/test/client/uaa/model/ProfileInfoResponse.java
java/com/test/client/uaa/model/UserDTO.java

UaaApiClient.java

package com.test.client.uaa;

import com.test.client.AuthorizedFeignClient;
import com.test.client.uaa.api.UaaApi;

@AuthorizedFeignClient(name="${feignclient.uaa.service-name:uaa}")
public interface UaaApiClient extends UaaApi {
}

It would also be nice if you could specify the DateTime class to use in the generated model classes. I have to do a search/replace to change to ZonedDateTime every time I update my model.

FeignClient is not using the JHipster Registry

Let's say I have two microservices:

  • NumberAPI has no DB, nothing, and just generates an ISBN number
  • BookAPI does CRUD operations on a Book entity. The book has a title, a price and an ISBN. The BookAPI invokes the Number API so it can get an ISBN number when creating a Book

In Book API I use the jhipster-swagger-cli to generate a Java client to invoke the Number API. The generated code for the FeignClient is :

@FeignClient(name="${numberapi.name:numberapi}", url="${numberapi.url:https://localhost:8081}", configuration = ClientConfiguration.class)
public interface ApiApiClient extends ApiApi {

As you can see, the URL of Number API is hardcoded (https://localhost:8081) and the numberapi.url variable being not set, it doesn't use the JHipster registry. Thanks to @jdubois I managed to get it work just by putting the registry name of the service:

@FeignClient(value = "numberapi")
public interface ApiApiClient extends ApiApi {
}

Shouldn't this be the default when doing microservices ? Is this the recommended way ?

Thanks

Difficulties to generate client

Dear all,
I have tried to generate the client from a previous jhispter application.
I have errors.
I have been looking for a swagger.json file in my jhipster app it seems not to be present.
Is there something that i have missed?

Is http://localhost:8080/v2/api-docs equivalent to swagger.json ?

Is src/main/webapp/app/app.module.js equivalent to src/main/webapp/app/app.module.ts ?

Thanks for your explanation.

`Welcome to the JHipster swagger-cli generator! v2.0.5

Reading the JHipster project configuration for your module
? Where is your Swagger/OpenAPI spec (URL or path) ? http://localhost:8080/v2/api-docs
? What is the unique name for your API client ? blockchainergyapiclient
? Select which type of API client to generate front-end client, back-end client
? Do you want to save this config for future reuse ? Yes
Generating front end code for blockchainergyapiclient (http://localhost:8080/v2/api-docs)

Unable to find src/main/webapp/app/app.module.js or missing required jhipster-needle. Reference to blockchainergyapiclient not added to JHipster app.

TypeError: this.debug is not a function
at Object.addAngularJsModule (/volatile/home/fl218080/gitBlockChain/blockchainergy-poc/blockchainergy-webapp2/node_modules/generator-jhipster/generators/generator-base.js:746:18)
at constructor. (/usr/lib/node_modules/generator-jhipster-swagger-cli/generators/app/index.js:272:26)
at Array.forEach (native)
at constructor. (/usr/lib/node_modules/generator-jhipster-swagger-cli/generators/app/index.js:250:47)
at Array.forEach (native)
at constructor.callSwaggerCodegen (/usr/lib/node_modules/generator-jhipster-swagger-cli/generators/app/index.js:248:40)
at Object. (/usr/lib/node_modules/generator-jhipster-swagger-cli/node_modules/yeoman-generator/lib/base.js:436:25)
at /usr/lib/node_modules/generator-jhipster-swagger-cli/node_modules/yeoman-generator/node_modules/run-async/index.js:25:25
at /usr/lib/node_modules/generator-jhipster-swagger-cli/node_modules/yeoman-generator/node_modules/run-async/index.js:24:19
at /usr/lib/node_modules/generator-jhipster-swagger-cli/node_modules/yeoman-generator/lib/base.js:448:8`

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.