Swagger Auto Generation using Annotations

Posted by

Swagger plugin is used to generate Web Services Contract for REST Services (its like a WSDL for SOAP) from the code by adding few annotations

Existing API’s can be easily migrated on to swagger with very little code changes..

 Swagger contract can be shared with clients who can refer the contract to code the services, also the clients can trigger these services from swagger UI.

There are two ways in which swagger can be generated and used, both ways are explained below in detail.

– Generate Swagger at compile time and deploy it on different Web server/App Server.

Only disadvantage is you will not able to trigger services from Swagger instances as there both the swagger and WebApp is running on different servers,but still this can be fixed by Adding a web server like apache or nginx and configure reverse proxy for all web service calls.

or you can download complete project from here https://drive.google.com/open?id=0Bw3J992vRA_DaF83MVBMSi12Zlk

– Generate Swagger at runtime.

Swagger code is deployed along with the our services (It may add negligible over head on the application transaction response time)

Generate Swagger at compile time:

1. Create Web Application Project using maven as below

mvn archetype:generate -DarchetypeArtifactId=jersey-heroku-webapp  -DarchetypeGroupId=org.glassfish.jersey.archetypes -DinteractiveMode=false -DgroupId=com.example -DartifactId=simple-heroku-webapp -Dpackage=com.example -DarchetypeVersion=2.25.1

2. Add  required Maven dependancies

<dependency>
	<groupId>io.swagger</groupId>
	<artifactId>swagger-annotations</artifactId>
	<version>1.5.8</version>
</dependency>

<plugin>
	<groupId>com.github.kongchen</groupId>
	<artifactId>swagger-maven-plugin</artifactId>
	<version>3.1.2</version>
	<configuration>
		<apiSources>
			<apiSource>
				<springmvc>false</springmvc>
				<locations>com.devops</locations>
				<schemes>http,https</schemes>
				<host>http://localhost:8081</host>
				<basePath>/swagger</basePath>
				<info>
					<title>Swagger spec for our REST API</title>
					<version>swagger v1</version>
					<description>This is a sample spec for our REST API</description>
					<termsOfService>
					</termsOfService>
					<contact>
						<email></email>
						<name></name>
						<url></url>
					</contact>
					<license>
						<url></url>
						<name>Company Licence</name>
					</license>
				</info>
				<swaggerDirectory>src/main/webapp/</swaggerDirectory>
			</apiSource>
		</apiSources>
	</configuration>
	<executions>
		<execution>
			<phase>compile</phase>
			<goals>
				<goal>generate</goal>
			</goals>
		</execution>
	</executions>
</plugin>

3. Sample Rest Controller class 

@Path("/swagger")
@Api(value = "/swagger", description = "Rest api for GET swagger", produces = MediaType.APPLICATION_JSON)
@Produces({ MediaType.APPLICATION_JSON })
class SwaggerController {
	@ApiOperation(value = "XXXXXXXXX", httpMethod = HttpMethod.GET, notes = "Fetch the uuid of the collection", response = Response.class)
	@ApiResponses(value = { @ApiResponse(code = 200, message = "Element found"),
			@ApiResponse(code = 404, message = "Element not found"),
			@ApiResponse(code = 500, message = "Server error due to encoding"),
			@ApiResponse(code = 400, message = "Bad request: decoding error"),
			@ApiResponse(code = 412, message = "Prereq: Required data not found") })
	public Response getUUID(@ApiParam(value = "UUID of the element", required = true) @PathParam("uuid") String uuid) {
		return Response.ok(uuid).build();

	}

	@ApiOperation(value = "Get uuid", httpMethod = HttpMethod.POST, notes = "Fetch the uuid of the collection", response = Response.class)
	@ApiResponses(value = { @ApiResponse(code = 200, message = "Element found"),
			@ApiResponse(code = 404, message = "Element not found"),
			@ApiResponse(code = 500, message = "Server error due to encoding"),
			@ApiResponse(code = 400, message = "Bad request: decoding error"),
			@ApiResponse(code = 412, message = "Prereq: Required data not found") })
	public Response getUUIDPost() {
		return Response.ok(getUUID(null)).build();

	}
}

4.  Sample swagger Json Generated 

{
  "swagger": "2.0",
  "info": {
    "description": "This is a sample spec for our REST API",
    "version": "swagger v1",
    "title": "Swagger spec for our REST API",
    "contact": {},
    "license": {
      "name": "Company Licence"
    }
  },
  "host": "http://localhost:8081",
  "basePath": "/swagger",
  "tags": [
    {
      "name": "swagger",
      "description": "Rest api for GET swagger"
    }
  ],
  "schemes": [
    "http",
    "https"
  ],
  "paths": {
    "/swagger": {
      "get": {
        "tags": [
          "swagger"
        ],
        "summary": "XXXXXXXXX",
        "description": "Fetch the uuid of the collection",
        "operationId": "getUUID",
        "produces": [
          "application/json"
        ],
        "parameters": [
          {
            "name": "uuid",
            "in": "path",
            "description": "UUID of the element",
            "required": true,
            "type": "string"
          }
        ],
        "responses": {
          "200": {
            "description": "Element found"
          },
          "400": {
            "description": "Bad request: decoding error"
          },
          "404": {
            "description": "Element not found"
          },
          "412": {
            "description": "Prereq: Required data not found"
          },
          "500": {
            "description": "Server error due to encoding"
          }
        }
      },
      "post": {
        "tags": [
          "swagger"
        ],
        "summary": "Get uuid",
        "description": "Fetch the uuid of the collection",
        "operationId": "getUUIDPost",
        "produces": [
          "application/json"
        ],
        "responses": {
          "200": {
            "description": "Element found"
          },
          "400": {
            "description": "Bad request: decoding error"
          },
          "404": {
            "description": "Element not found"
          },
          "412": {
            "description": "Prereq: Required data not found"
          },
          "500": {
            "description": "Server error due to encoding"
          }
        }
      }
    }
  }
}

5. Lets deploy swagger on standalone jetty/tomcat

– Checkout the dist folder of the swagger-ui source code from Github https://github.com/swagger-api/swagger-ui/tree/master/dist.

– Copy the dist folder in to root directory of you server

– Edit the index.html file and replace the pet store URL http://petstore.swagger.io/v2/swagger.json with our API spec URL : http://localhost:8080/swagger.json

– Load swagger http://localhost:8080/

Leave a Reply

Your email address will not be published.