Code Monkey home page Code Monkey logo

binder-swagger-java's Introduction

binder-swagger-java

Build Status

Given the swagger.json, swagger ui can dynamically build the web client, to enable online browsing your APIs, sending request and receiving response from your rest services.

binder-swagger-java was designed to help construct the swagger object, corresponding to swagger.json, and let it accessible from swagger ui or other http visitors.

Why another wheel?

We used many dynamic data structures (json, map, list, etc.) as API inbound/outbound parameters, didn't define java beans (static types), in our projects. And existing swagger solutions, e.g. springfox, don't support dynamic data structures, and can't be enhanced to support them.

So, I created binder-swagger-java, which enable to use form-binder-java to define dynamic data structures, and use them in swagger API docs.

p.s. binder-swagger-java based on swagger-models directly, allow to operate the swagger object directly when necessary, so it's more expressive in theory.

How to use

  1. add the dependency to your project:
<dependency>
  <groupId>com.github.tminglei</groupId>
  <artifactId>binder-swagger-java</artifactId>
  <version>0.5.0</version>
</dependency>
  1. define and register your api operations:
// in `PetResource.java`
static Mapping<?> petStatus = text(oneOf(Arrays.asList("available", "pending", "sold")))
    .$ext(o -> ext(o).desc("pet status in the store"));
static Mapping<?> pet = mapping(
    field("id", vLong().$ext(o -> ext(o).desc("pet id"))),
    field("name", text(required()).$ext(o -> ext(o).desc("pet name"))),
    field("category", attach(required()).to(mapping(
            field("id", vLong(required())),
            field("name", text(required()))
    )).$ext(o -> ext(o).refName("category").desc("category belonged to"))),
    field("photoUrls", list(text()).$ext(o -> ext(o).desc("pet's photo urls"))),
    field("tags", list(text()).$ext(o -> ext(o).desc("tags for the pet"))),
    field("status", petStatus)
).$ext(o -> ext(o).refName("pet").desc("pet info"));

static {
    operation("post", "/pet")
        .summary("create a pet")
        .tag("pet")
        .parameter(param(pet).in("body"))
        .response(200, response().description("success"))
        .response(400, response())
    ;
}
@POST
public Response addPet(String data) throws BadRequestException, SQLException {
...
  1. supplement your other swagger info:
// in `Bootstrap.java`
static {  // for swagger
	swagger().info(info()
	      .title("Swagger Sample App")
	      .description("This is a sample server Petstore server.  You can find out more about Swagger " +
		      "at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).  For this sample, " +
		      "you can use the api key `special-key` to test the authorization filters.")
	      .termsOfService("http://swagger.io/terms/")
	      .contact(contact().email("[email protected]"))
	      .license(license().name("Apache 2.0")
		              .url("http://www.apache.org/licenses/LICENSE-2.0.html")
	      )
	).host("localhost:8002")
	.basePath("/api")
	.consumes("application/json")
	.produces("application/json")
	.securityDefinition("api_key", apiKeyAuth("api_key", In.HEADER))
	.securityDefinition("petstore_auth", oAuth2()
		      .implicit("http://petstore.swagger.io/api/oauth/dialog")
		      .scope("read:pets", "read your pets")
		      .scope("write:pets", "modify pets in your account")
	).tag(tag("pet").description("Everything about your Pets")
		      .externalDocs(externalDocs().description("Find out more").url("http://swagger.io"))
	).tag(tag("store").description("Access to Petstore orders")
	).tag(tag("user").description("Operations about user")
	      .externalDocs(externalDocs().description("Find out more about our store").url("http://swagger.io"))
	);
}
  1. configure the filter, which will serv the swagger.json:
// in `web.xml`
<filter>
    <filter-name>SwaggerFilter</filter-name>
    <filter-class>com.github.tminglei.swagger.SwaggerFilter</filter-class>
    <!-- configure your extended swagger helper
    <init-param>
        <param-name>my-extended-swagger-helper</param-name>
        <param-value>com.mycompany.pkg.MySwaggerHelper</param-value>
    </init-param>
    -->
    <init-param>
        <param-name>scan-packages-and-classes</param-name>
        <param-value>com.example.resource; com.example.Bootstrap</param-value>
    </init-param>
    <!-- specify the path to fetch your swagger json, default '/swagger.json'
    <init-param>
        <param-name>swagger-path</param-name>
        <param-value>/swagger.json</param-value>
    </init-param>
    -->
    <!-- enable/disable swagger, default value: true
    <init-param>
        <param-name>enabled</param-name>
        <param-value>false</param-value>
    </init-param>
    -->
</filter>
<filter-mapping>
    <filter-name>SwaggerFilter</filter-name>
    <url-pattern>/api/*</url-pattern><!-- keep consistent with the jersey servlet mapping -->
</filter-mapping>
...

NOTES: if you extend the MSwaggerHelper and configure it here, pls ensure SwaggerFilter to be loaded eariler, that is, ensure the swagger helper to be set to SwaggerContext before other class scanner started working.

That's all. Enjoy it!

For more usage details, pls check the example project here.

License

The BSD License, Minglei Tu <[email protected]>

binder-swagger-java's People

Contributors

tminglei avatar

Watchers

 avatar

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.