Home » Core Java » Java Swagger Tutorial

About Mary Zheng

Mary Zheng
Mary has graduated from Mechanical Engineering department at ShangHai JiaoTong University. She also holds a Master degree in Computer Science from Webster University. During her studies she has been involved with a large number of projects ranging from programming and software engineering. She works as a senior Software Engineer in the telecommunications sector where she acts as a leader and works with others to design, implement, and monitor the software solution.

Java Swagger Tutorial

In this article, we will explain Java Swagger through a tutorial with examples.

1. Introduction

Swagger was first released in 2011 to ease the Restful API documentation and client SDK generation during the development of Wordnik‘s products. In 2015, SmartBear software company donated the Swagger specification to open source which is sponsored by Linux Foundation, Google, IBM, and Microsoft. The swagger specification was renamed to OpenAPI specification in 2016. Swagger is a set of open-source tools built around the OpenAPI specification that helps to design, building, documenting, and consuming REST API. In this example, I will demonstrate:

  • How to add swagger documentation to an existing spring boot Rest application.
  • How to test Rest APIs via Swagger UI.
  • How to use Swagger Editor to convert Swagger’s definition to OpenAPI definition.
  • How to generate source code from Swagger’s definition file.

2. Technologies Used

The example code in this article was built and run using:

  • Java 8
  • Maven 3.3.9
  • Eclipse Oxygen
  • Spring boot
  • Swagger

3. Spring boot Rest API Project

In this step, I will build a spring boot application that provides Rest APIs to create an item and retrieve all the items.

Click here for step-by-step instructions on how to create a Spring boot Rest Service. Skip to step 4 if you knew this already.

3.1 Dependencies

I will include dependencies in the pom.xml.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>org.jcg.zheng</groupId>
	<artifactId>sb-swagger-demo</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>sb-swagger-demo</name>
	<url>http://maven.apache.org</url>


	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.1.RELEASE</version>
	</parent>
	<properties>
		<java.version>1.8</java.version>
		<maven.compiler.source>${java.version}</maven.compiler.source>
		<maven.compiler.target>${java.version}</maven.compiler.target>
	</properties>
	<dependencies>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<scope>runtime</scope>
		</dependency>

	</dependencies>
	<build>
		<finalName>sb-swagger-demo</finalName>
	</build>
</project>

3.2 Spring Boot Application

In this step, I will create a SbApplication class which annotates with @SpringBootApplication and @EnableJpaRepostiories.

SbApplication.java

package jcg.zheng.demo.swagger;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication
@EnableJpaRepositories(basePackages = "jcg.zheng.demo")
public class SbApplication {
	public static void main(String[] args) {
		SpringApplication.run(SbApplication.class, args);
	}
}

3.3 Rest Controller

In this step, I will create an ItemController class which annotates with @RestController and defines two Restful APIs.

ItemController.java

package jcg.zheng.demo.swagger.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jcg.zheng.demo.swagger.model.ItemData;

@RestController
@RequestMapping(value = ItemController.ROOT_PATH)
public class ItemController {

	public static final String ROOT_PATH = "/item";
	
	@Autowired
	ItemDataRepository dao;

	@PostMapping
	public Integer createItem( @RequestBody ItemData itemData) {
		return dao.save(itemData).getId();
	}

	@GetMapping(value = "/all")
	public List getItems() {
		return dao.findAll();
	}
}

3.4 Repository

In this step, I will create an ItemDataRepository class which annotates with @Repository and @Transactional.

ItemDataRepository.java

package jcg.zheng.demo.swagger.controller;

import javax.transaction.Transactional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import jcg.zheng.demo.swagger.model.ItemData;

@Repository
@Transactional
public interface ItemDataRepository extends JpaRepository<ItemData, Integer> {

}

3.5 ItemData

In this step, I will create an ItemData class which annotates with @Entity and @Table.

ItemData.java

package jcg.zheng.demo.swagger.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "ITEM")
public class ItemData {

	private boolean hasError;

	@Id
	@GeneratedValue
	@Column(name = "ID")
	private Integer id;

	private String name;

	public Integer getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public void setName(String name) {
		this.name = name;
	}

	public boolean isHasError() {
		return hasError;
	}

	public void setHasError(boolean hasError) {
		this.hasError = hasError;
	}

}

3.6 Test Rest API via Postman

In this step, I will start the application, monitor the server log. Once the server is started, then use Postman to test both GET and POST APIs. Navigate to http://localhost:8080/item/getall, you should see an empty list.

Java Swagger - Get All Items
Figure 1 Get All Items

Use Postman to create a new item.

Java Swagger - Create an Item
Figure 2 Create an Item

Use Postman to retrieve all items. You should see the newly created item.

Java Swagger - Get All Items
Figure 3 Get All Items

4. Add Swagger Documentation

In this step, I will add swagger to the spring boot application with two steps:

  • Add Swagger dependencies.
  • Add Swagger configuration and annotation.

4.1 Add Dependency

In this step, I will edit the POM.xml to add Springfox swagger dependency. Springfox creates JSON API documentation for Rest API built with Spring.

updated pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>org.jcg.zheng</groupId>
	<artifactId>sb-swagger-demo</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>sb-swagger-demo</name>
	<url>http://maven.apache.org</url>


	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.1.RELEASE</version>
	</parent>
	<properties>
		<java.version>1.8</java.version>
		<maven.compiler.source>${java.version}</maven.compiler.source>
		<maven.compiler.target>${java.version}</maven.compiler.target>
		<springfox-version>2.9.2</springfox-version>
	</properties>
	<dependencies>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<scope>runtime</scope>
		</dependency>

	 	<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>${springfox-version}</version>
		</dependency>

		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>${springfox-version}</version>
		</dependency> 
	</dependencies>
	<build>
		<finalName>sb-swagger-demo</finalName>
	</build>
</project>

Note: line 42, 48: Springfox swagger dependencies.

4.2 Add Swagger Configuration

In this step, I will create a SwaggerDocConfig class which annotates with @Configuration and @EnableSwagger2.

SwaggerDocConfig.java

package jcg.zheng.demo.swagger;

import static springfox.documentation.builders.PathSelectors.regex;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import jcg.zheng.demo.swagger.controller.ItemController;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerDocConfig {

	private static final String ALL_CHILD = ".*";

	private ApiInfo metadata() {
		return new ApiInfoBuilder().title("Swagger Demo").description("API reference guide for developers")
				.termsOfServiceUrl("https://www.javacodegeeks.com/").contact(new Contact("", "", "mary.zheng@jcg.org"))
				.version("1.0").build();
	}

	@Bean
	public Docket itemApi() {
		return new Docket(DocumentationType.SWAGGER_2).groupName("Item API").apiInfo(metadata()).select()
				.paths(regex(ItemController.ROOT_PATH + ALL_CHILD)).build();

	}

}

I will edit the ItemController class to add @ApiParam for the Rest API.

Updated ItemController.java

package jcg.zheng.demo.swagger.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.ApiParam;
import jcg.zheng.demo.swagger.model.ItemData;

@RestController
@RequestMapping(value = ItemController.ROOT_PATH)
public class ItemController {

	public static final String ROOT_PATH = "/item";

	@Autowired
	ItemDataRepository dao;

	@PostMapping
	public Integer createItem(@ApiParam(value = "createRequest", required = true) @RequestBody ItemData itemData) {
		return dao.save(itemData).getId();
	}

	@GetMapping(value = "/all")
	public List getItems() {
		return dao.findAll();
	}
}

Note: line 25, Swagger @ApiParam is added.

4.3 Test with Swagger UI

Now we can use Swagger UI as API documentation and testing tool.

Start the application, open a browser and navigate to http://localhost:8080/swagger-ui.html#/. You should see a Swagger UI as following screenshot.

Figure 4 Swagger UI

Now, we can see the API signature and test it with “Try it out” button.

4.4 Java Swagger Definition

In this step, I will copy the swagger definition from the http://localhost:8080/v2/api-docs?group=Item%20API and save it as a JSON file locally. It will be used to generate server side spring code at step 5.1.

swaggerDefinition.json

{
	"swagger": "2.0",
	"info": {
		"description": "API reference guide for developers",
		"version": "1.0",
		"title": "Swagger Demo",
		"termsOfService": "https://www.javacodegeeks.com/",
		"contact": {
			"email": "mary.zheng@jcg.org"
		}
	},
	"host": "localhost:8080",
	"basePath": "/",
	"tags": [{
		"name": "item-controller",
		"description": "Item Controller"
	}],
	"paths": {
		"/item": {
			"post": {
				"tags": ["item-controller"],
				"summary": "createItem",
				"operationId": "createItemUsingPOST",
				"consumes": ["application/json"],
				"produces": ["*/*"],
				"parameters": [{
					"in": "body",
					"name": "itemData",
					"description": "createRequest",
					"required": true,
					"schema": {
						"$ref": "#/definitions/ItemData"
					}
				}],
				"responses": {
					"200": {
						"description": "OK",
						"schema": {
							"type": "integer",
							"format": "int32"
						}
					},
					"201": {
						"description": "Created"
					},
					"401": {
						"description": "Unauthorized"
					},
					"403": {
						"description": "Forbidden"
					},
					"404": {
						"description": "Not Found"
					}
				},
				"deprecated": false
			}
		},
		"/item/all": {
			"get": {
				"tags": ["item-controller"],
				"summary": "getItems",
				"operationId": "getItemsUsingGET",
				"produces": ["*/*"],
				"responses": {
					"200": {
						"description": "OK",
						"schema": {
							"type": "array",
							"items": {
								"$ref": "#/definitions/ItemData"
							}
						}
					},
					"401": {
						"description": "Unauthorized"
					},
					"403": {
						"description": "Forbidden"
					},
					"404": {
						"description": "Not Found"
					}
				},
				"deprecated": false
			}
		}
	},
	"definitions": {
		"ItemData": {
			"type": "object",
			"properties": {
				"hasError": {
					"type": "boolean"
				},
				"id": {
					"type": "integer",
					"format": "int32"
				},
				"name": {
					"type": "string"
				}
			},
			"title": "ItemData"
		}
	}
}

5. Java Swagger Editor

The Swagger Editor is an open source editor to design, define and document RESTful APIs in the Swagger Specification. In this step, I will demonstrate:

  • Import Swagger specification
  • Convert Swagger specification to OpenAPI specification
  • Generate Source Code from Swagger specification

5.1 Import Swagger Specification

In this step, I will navigate to swagger editor at https://editor.swagger.io/, click on the File->Import File and import the saved swaggerDefintion.json file at step 4.4. It will automatically convert to YAML format and you can test API here with “Try it out” button.

Figure 5 Swagger Editor

5.2 Convert to OpenAPI

In this step, I will convert the swagger specification to OpenAPI 3 specification by clicking the Edit->Convert to OpenAPI 3. Save the OpenAPI specification.

openApiSpecification.yaml

openapi: 3.0.1
info:
  title: Swagger Demo
  description: API reference guide for developers
  termsOfService: https://www.javacodegeeks.com/
  contact:
    email: mary.zheng@jcg.org
  version: "1.0"
servers:
- url: //localhost:8080/
tags:
- name: item-controller
  description: Item Controller
paths:
  /item:
    post:
      tags:
      - item-controller
      summary: createItem
      operationId: createItemUsingPOST
      requestBody:
        description: createRequest
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ItemData'
        required: true
      responses:
        200:
          description: OK
          content:
            '*/*':
              schema:
                type: integer
                format: int32
        201:
          description: Created
          content: {}
        401:
          description: Unauthorized
          content: {}
        403:
          description: Forbidden
          content: {}
        404:
          description: Not Found
          content: {}
      deprecated: false
      x-codegen-request-body-name: itemData
  /item/all:
    get:
      tags:
      - item-controller
      summary: getItems
      operationId: getItemsUsingGET
      responses:
        200:
          description: OK
          content:
            '*/*':
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/ItemData'
        401:
          description: Unauthorized
          content: {}
        403:
          description: Forbidden
          content: {}
        404:
          description: Not Found
          content: {}
      deprecated: false
components:
  schemas:
    ItemData:
      title: ItemData
      type: object
      properties:
        hasError:
          type: boolean
        id:
          type: integer
          format: int32
        name:
          type: string

5.3 Code Generation

As you seen in the Swagger Editor menu, there are two menu items- Generate Server and Generate Client – to generate source code. There are more than 50 options for various languages. You can try it out yourself.

Note: generated code has some limitation. For example, it uses JDK7 for Java.

6. API First Application

In this step, I will use the swagger-codegen-cli.jar to generate a Spring boot project which has the stub code to implement the Rest API defined in the Swagger specification.

6.1 Generate Spring Boot Project

First, I will create a folder: api-first-sb, which has a sdk folder with a swagger-codegen-cli.jar file in it. Here is the folder layout:

C:\MaryZheng\Workspaces\jdk12\api-first-sb>dir
 Volume in drive C is OSDisk
 Volume Serial Number is 34CD-EFB3

 Directory of C:\MaryZheng\Workspaces\jdk12\api-first-sb

09/04/2020  08:04 PM              .
09/04/2020  08:04 PM              ..
09/04/2020  08:06 PM              sdk
09/04/2020  07:53 PM             2,100 swaggerDefinition.json
               1 File(s)          2,100 bytes
               3 Dir(s)  105,009,061,888 bytes free

C:\MaryZheng\Workspaces\jdk12\api-first-sb>dir sdk
 Volume in drive C is OSDisk
 Volume Serial Number is 34CD-EFB3

 Directory of C:\MaryZheng\Workspaces\jdk12\api-first-sb\sdk

09/04/2020  08:06 PM              .
09/04/2020  08:06 PM              ..
09/04/2020  07:55 PM              .swagger-codegen
07/31/2020  11:04 AM        14,316,576 swagger-codegen-cli.jar
               2 File(s)     14,317,291 bytes
               3 Dir(s)  105,008,869,376 bytes free

C:\MaryZheng\Workspaces\jdk12\api-first-sb>

Note:

  • line 5: folder: api-first-sb
  • line 10: swaggerDefinition.json
  • line 18: folder: sdk
  • line 23: swagger-codegen-cli.jar

6.2 Generated Project

I will execute the following command to generate spring boot project at sb-api-service folder for the swaggerDefinition.json file.

command

C:\MaryZheng\Workspaces\jdk12\api-first-sb\sdk>java -jar swagger-codegen-cli.jar generate -i ..\swaggerDefinition.json --api-package org.jcg.zheng.demo.api --model-package org.jcg.zheng.demo.model  --invoker-package org.jcg.zheng --group-id org.jcg.zheng --artifact-id swagger-api --artifact-version 0.0.1.SNAPSHOT -l spring -o ..\sb-api-service

output

[main] INFO io.swagger.parser.Swagger20Parser - reading from ../swaggerDefinition.json
[main] WARN io.swagger.codegen.ignore.CodegenIgnoreProcessor - Output directory does not exist, or is inaccessible. No file (.swagger-codegen-ignore) will be evaluated.
[main] INFO io.swagger.codegen.languages.AbstractJavaCodegen - Set base package to invoker package (org.jcg.zheng)
[main] INFO io.swagger.codegen.AbstractGenerator - writing file C:\MaryZheng\Workspaces\jdk12\api-first-sb\sdk\..\sb-api-service\src\main\java\org\jcg\zheng\demo\model\ItemData.java
[main] INFO io.swagger.codegen.AbstractGenerator - writing file C:\MaryZheng\Workspaces\jdk12\api-first-sb\sdk\..\sb-api-service\src\main\java\org\jcg\zheng\demo\api\ItemApiController.java
[main] INFO io.swagger.codegen.AbstractGenerator - writing file C:\MaryZheng\Workspaces\jdk12\api-first-sb\sdk\..\sb-api-service\src\main\java\org\jcg\zheng\demo\api\ItemApi.java
[main] INFO io.swagger.codegen.AbstractGenerator - writing file C:\MaryZheng\Workspaces\jdk12\api-first-sb\sdk\..\sb-api-service\pom.xml
[main] INFO io.swagger.codegen.AbstractGenerator - writing file C:\MaryZheng\Workspaces\jdk12\api-first-sb\sdk\..\sb-api-service\README.md
[main] INFO io.swagger.codegen.AbstractGenerator - writing file C:\MaryZheng\Workspaces\jdk12\api-first-sb\sdk\..\sb-api-service\src\main\java\io\swagger\configuration\HomeController.java
[main] INFO io.swagger.codegen.AbstractGenerator - writing file C:\MaryZheng\Workspaces\jdk12\api-first-sb\sdk\..\sb-api-service\src\main\java\org\jcg\zheng\Swagger2SpringBoot.java
[main] INFO io.swagger.codegen.AbstractGenerator - writing file C:\MaryZheng\Workspaces\jdk12\api-first-sb\sdk\..\sb-api-service\src\main\java\org\jcg\zheng\RFC3339DateFormat.java
[main] INFO io.swagger.codegen.AbstractGenerator - writing file C:\MaryZheng\Workspaces\jdk12\api-first-sb\sdk\..\sb-api-service\src\main\resources\application.properties
[main] INFO io.swagger.codegen.AbstractGenerator - writing file C:\MaryZheng\Workspaces\jdk12\api-first-sb\sdk\..\sb-api-service\src\main\java\org\jcg\zheng\demo\api\ApiException.java
[main] INFO io.swagger.codegen.AbstractGenerator - writing file C:\MaryZheng\Workspaces\jdk12\api-first-sb\sdk\..\sb-api-service\src\main\java\org\jcg\zheng\demo\api\ApiResponseMessage.java
[main] INFO io.swagger.codegen.AbstractGenerator - writing file C:\MaryZheng\Workspaces\jdk12\api-first-sb\sdk\..\sb-api-service\src\main\java\org\jcg\zheng\demo\api\NotFoundException.java
[main] INFO io.swagger.codegen.AbstractGenerator - writing file C:\MaryZheng\Workspaces\jdk12\api-first-sb\sdk\..\sb-api-service\src\main\java\org\jcg\zheng\demo\api\ApiOriginFilter.java
[main] INFO io.swagger.codegen.AbstractGenerator - writing file C:\MaryZheng\Workspaces\jdk12\api-first-sb\sdk\..\sb-api-service\src\main\java\io\swagger\configuration\SwaggerDocumentationConfig.java
[main] INFO io.swagger.codegen.AbstractGenerator - writing file C:\MaryZheng\Workspaces\jdk12\api-first-sb\sdk\..\sb-api-service\src\main\java\io\swagger\configuration\CustomInstantDeserializer.java
[main] INFO io.swagger.codegen.AbstractGenerator - writing file C:\MaryZheng\Workspaces\jdk12\api-first-sb\sdk\..\sb-api-service\src\main\java\io\swagger\configuration\JacksonConfiguration.java
[main] INFO io.swagger.codegen.AbstractGenerator - writing file C:\MaryZheng\Workspaces\jdk12\api-first-sb\sdk\..\sb-api-service\.swagger-codegen-ignore
[main] INFO io.swagger.codegen.AbstractGenerator - writing file C:\MaryZheng\Workspaces\jdk12\api-first-sb\sdk\..\sb-api-service\.swagger-codegen\VERSION

Note: line 5. ItemApiController stub need to update based on business requirements.

6.3 Edit Generated File

Import the generated project into Eclipse. It should have no compiler error. Here is the imported project in Eclipse IDE.

Figure 6 Project Layout

Update the following items:

  • rename the package io.swagger.configuration to org.jcg.zheng.config
  • update pom.xml to JDK 1.8 and springfox version to 2.9.2

Generated ItemController.java

package org.jcg.zheng.demo.api;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.jcg.zheng.demo.model.ItemData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;

import com.fasterxml.jackson.databind.ObjectMapper;

import io.swagger.annotations.ApiParam;

@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2020-09-04T20:14:30.860-05:00")

@Controller
public class ItemApiController implements ItemApi {

	private static final Logger log = LoggerFactory.getLogger(ItemApiController.class);

	private final ObjectMapper objectMapper;

	private final HttpServletRequest request;
	
	@org.springframework.beans.factory.annotation.Autowired
	public ItemApiController(ObjectMapper objectMapper, HttpServletRequest request) {
		this.objectMapper = objectMapper;
		this.request = request;
	}

	public ResponseEntity<Integer> createItemUsingPOST(
			@ApiParam(value = "createRequest", required = true) @Valid @RequestBody ItemData itemData) {
		String accept = request.getHeader("Accept");
		if (accept != null && accept.contains("")) {
			try {
				return new ResponseEntity<Integer>(objectMapper.readValue("", Integer.class),
						HttpStatus.NOT_IMPLEMENTED);
			} catch (IOException e) {
				log.error("Couldn't serialize response for content type ", e);
				return new ResponseEntity<Integer>(HttpStatus.INTERNAL_SERVER_ERROR);
			}
		}

		return new ResponseEntity<Integer>(HttpStatus.NOT_IMPLEMENTED);
	}

	public ResponseEntity<List<ItemData>> getItemsUsingGET() {
		String accept = request.getHeader("Accept");
		if (accept != null && accept.contains("")) {
			try {
				return new ResponseEntity<List<ItemData>>(objectMapper.readValue("", List.class),
						HttpStatus.NOT_IMPLEMENTED);
			} catch (IOException e) {
				log.error("Couldn't serialize response for content type ", e);
				return new ResponseEntity<List<ItemData>>(HttpStatus.INTERNAL_SERVER_ERROR);
			}
		}

		return new ResponseEntity<List<ItemData>>(HttpStatus.NOT_IMPLEMENTED);
	}

}

Note: the highlighted methods need to be changed according to the business logic. At this moment, when you clicking “Try it out” at Swagger UI, you will see the error message in the server log because we haven’t change it yet.

6.4 Edit ItemApiConstroller

For a demonstration purpose, I will update the generated ItemApiController to read and save data into a static list.

Edited ItemApiController.java

package org.jcg.zheng.demo.api;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.jcg.zheng.demo.model.ItemData;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;

import com.fasterxml.jackson.databind.ObjectMapper;

import io.swagger.annotations.ApiParam;

@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2020-09-04T20:14:30.860-05:00")

@Controller
public class ItemApiController implements ItemApi {

	private static List<ItemData> items = new ArrayList<>();

	@org.springframework.beans.factory.annotation.Autowired
	public ItemApiController(ObjectMapper objectMapper, HttpServletRequest request) {

	}

	public ResponseEntity<Integer> createItemUsingPOST(
			@ApiParam(value = "createRequest", required = true) @Valid @RequestBody ItemData itemData) {
		items.add(itemData);

		return ResponseEntity.ok().header("createItem", "Done").body(itemData.getId());
	}

	public ResponseEntity<List<ItemData>> getItemsUsingGET() {
		return ResponseEntity.ok().header("getItems", "Done").body(items);
	}

}

After this change, you can start the spring boot application. Navigate to the Swagger UI at http://localhost:8080/swagger-ui.html#/. It shows that newly generated spring boot project has the services matching the swagger definition file and working as desired.

7. Summary

In this example, I demonstrated:

  • How to add swagger to an existing spring boot Rest project.
  • How to use Swagger UI to test the Rest API.
  • How to generate source code for a spring boot application based on swagger definition file.

8. Download the Source Code

This example consists of two Maven project which demonstrates how to use Swagger in a Spring boot project.

Download
You can download the full source code of this example here: Java Swagger Tutorial

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments