Giter Site home page Giter Site logo

agliznetsov / swagger-tools Goto Github PK

View Code? Open in Web Editor NEW
1.0 2.0 1.0 380 KB

Code generator to produce java client and server mappings from Swagger / OpenAPI REST API definition.

License: MIT License

Java 99.73% Shell 0.01% HTML 0.26%
swagger java open-api open-api-v3 maven-plugin code-generation oas

swagger-tools's Introduction

swagger-tools

Build Status Download CLI

Overview

This project provides a set of tools to generate java code from API definition.

Source

  • Swagger 2.0 or OpenAPI 3.0 API definition in json/yaml format
  • Extensions
    • x-ignore to exclude operations from the code generation process
    • x-ignore-server to exclude operations from the server code generation process
    • x-ignore-server-client to exclude operations from the client code generation process
    • x-name to specify OpenAPI 3 requestBody parameter name
    • x-base-path to specify OpenAPI 3 API base path
    • x-response-entity to make Client/Server return Spring ResponseEntity object
    • x-model-package to specify package name for the model classes

Targets

  • Model classes. Supported dialects:
    • Jackson2
  • Java client SDK, can be used for unit testing or to create java client applications. Supported dialects:
    • Spring RestTemplate
    • Spring WebClient
    • Apache HttpClient
  • Server API interfaces with HTTP mapping annotations. Supported dialects:
    • Spring WebMVC
    • Spring Webflux
    • JAX-RS

Run from command line

To get list of arguments:

java -jar swagger-tools-cli.jar

To generate models and client code:

java -jar swagger-tools-cli.jar \
--source.location=swagger.yaml \
--target.model.location=./generated \
--target.model.model-package=com.example.model \
--target.client.location=./generated \
--target.client.model-package=com.example.model \
--target.client.client-package=com.example.client \

Run from maven

<build>
    <plugins>
        <plugin>
            <groupId>com.github.agliznetsov.swagger-tools</groupId>
            <artifactId>swagger-tools-maven-plugin</artifactId>
            <version>0.2.0</version>
            <executions>
                <execution>
                    <id>petstore</id>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                    <configuration>
                        <sources>
                            <param>${project.basedir}/src/main/resources/petstore.yaml</param>
                        </sources>
                        <options>
                            <target.model.location>${project.build.directory}/generated-sources/swagger</target.model.location>
                            <target.model.model-package>org.swaggertools.demo.model</target.model.model-package>

                            <target.client.location>${project.build.directory}/generated-sources/swagger</target.client.location>
                            <target.client.model-package>org.swaggertools.demo.model</target.client.model-package>
                            <target.client.client-package>org.swaggertools.demo.client</target.client.client-package>
                        </options>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

Plugin configuration parameters:

  • skip: Skip code generation
  • help: Print the list of options
  • options: Key/Value map of arguments for the code generator. Same as for the commandline version.

Check also a complete sample application: demo-webmvc

Run from gradle

There is no specific gradle plugin yet, but you can run code generator from gradle using command line version:

configurations {
   swagger
}
 
dependencies {
   swagger 'com.github.agliznetsov.swagger-tools:swagger-tools-cli:0.8.3'
}
 
task "swagger-generate"(type: JavaExec) {
   classpath = configurations.swagger
   main = 'org.swaggertools.cli.Generator'
   args = [
         "--source.location", "src/main/resources/swagger.yaml",
         "--target.model.location", "src/main/java",
         "--target.model.model-package", "com.example.model",
   ]
}

Extensions

Additional targets can be added via java ServiceLoader:

  • Implement Target interface
  • List it in the META-INF/services
  • Add your jar file to the classpath of the CLI or maven plugin

swagger-tools's People

Contributors

agliznetsov avatar netonlive avatar

Stargazers

 avatar

Watchers

 avatar  avatar

Forkers

dvdeurse

swagger-tools's Issues

Polymorphic list items in request body

Consider the following spec:

paths:
  /animals:
    post:
      operationId: createAnimals
      requestBody:
        description: animal
        content:
          application/json:
            schema:
              type: array
              items:
                $ref: '#/components/schemas/Animal'
        required: true

components:
    Animal:
      type: object
      properties:
        name:
          type: string
      discriminator:
        propertyName: '@type'

    Dog:
      allOf:
        - $ref: '#/components/schemas/Animal'

    Cat:
      allOf:
        - $ref: '#/components/schemas/Animal'

When you generate a client for this spec, it will fail because the generated code is not providing the type information to the client library (e.g. resttemplate, webclient). Jackson needs this information as it cannot know the type from an incoming List of objects.

The invokeApi method (in this example for resttemplate) should be something similar to (note the additional requestBodyTypeRef param):

    protected <T, U> ResponseEntity<T> invokeAPI(String path, String method, Map<String, String> urlVariables, MultiValueMap<String, String> queryParams, Object body, ParameterizedTypeReference<U> requestBodyTypeRef, ParameterizedTypeReference<T> returnType) {
        URI baseUrl = restTemplate.getUriTemplateHandler().expand(basePath);
        URI uri = UriComponentsBuilder
                .fromUri(baseUrl)
                .path(path)
                .queryParams(queryParams)
                .buildAndExpand(urlVariables)
                .toUri();
        RequestEntity.BodyBuilder requestBuilder = RequestEntity.method(HttpMethod.resolve(method), uri);
        customizeRequest(requestBuilder);
        RequestEntity<Object> requestEntity = requestBuilder.body(body, requestBodyTypeRef.getType());
        return restTemplate.exchange(requestEntity, returnType);
    }

Use of Flux in Webclient dialect

Consider the following spec, where we declare a GET that returns a list of items:

/list:
  get:
    tags:
      - Example
    operationId: getExampleList
    responses:
      200:
        description: OK
        content:
          application/json:
            schema:
              type: array
              items:
                $ref: '#/components/schemas/Example'

When generating a client for this method, using the WebClient dialect, it results in the following code fragment:

public Mono<List<Example>> getExampleList() {
    ParameterizedTypeReference<List<Example>> typeRef = new ParameterizedTypeReference<List<Example>>(){};
    return invokeAPI("/list", "GET", createUrlVariables(), createQueryParameters(), null).bodyToMono(typeRef);
}

While I would expect the following:

public Flux<Example> getExampleList() {
    return invokeAPI("/list", "GET", createUrlVariables(), createQueryParameters(), null).bodyToFlux(Example.class);
}

Inherited classes should have callSuper=true in toString lombok annotation

Hi Andrey,

How are you?
We still use this plugin to generate our rest api classes. :)
And so when the inherited class is generated the lombok ToString annotation is added without a callSuper.
And so the properties of the super class are not added in the string representation.

f.e.

`
package com.evs.phoenix.transform.payloads;

import com.fasterxml.jackson.annotation.JsonProperty;
import java.lang.Boolean;
import java.lang.String;
import lombok.EqualsAndHashCode;
import lombok.ToString;

@tostring
@EqualsAndHashCode
public class FileLocation extends Location {
@JsonProperty("_type")
private final String type = "FileLocation";

@JsonProperty("present")
private Boolean present;

public String getType() {
    return type;
}

public Boolean isPresent() {
    return present;
}

public void setPresent(Boolean present) {
    this.present = present;
}

}
`

Default values for enums

The following spec shows the use of a default value for the enumProp field:

EnumExample:
  type: string
  enum:
    - One
    - Two

ObjectExample:
  type: object
  properties:
    enumProp:
      $ref: '#/components/schemas/EnumExample'
      default: 'One'

When generating the model classes, the 'default' value is not taken into account. It does work for simple datatypes though, but not for enumeration types that are referenced.

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.