Everything You Need To Know About Swagger

Dependencies :

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>

Swagger configuration :

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2);
}
}
@RestController
public class UserController {
@Autowired
private UserDaoService userDaoService;
@GetMapping(value = "/users", produces {MediaType.APPLICATION_XML_VALUE,MediaType.APPLICATION_JSON_VALUE})
public List<User> retreiveAllUsers() {
return userDaoService.findAll();
}
@GetMapping("users/{id}")
public User retreiveUser(@PathVariable Integer id) {
try {
User user = userDaoService.findOne(id);
if (user == null) {
throw new UserNotFoundException("id-" + id);
}
return user;
} catch (UserNotFoundException ex) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Id not found");
}
}
@PostMapping(value = "/users")
public ResponseEntity createUser(@RequestBody @Valid User user) {
User savedUser = null;
try {
savedUser = userDaoService.save(user);
return new ResponseEntity(HttpStatus.CREATED);
} catch (Exception ex) {
ex.printStackTrace();
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
}@DeleteMapping("/users/{id}")
public User deleteById(@PathVariable int id) {
try {
User user = userDaoService.deleteUser(id);
return user;
} catch (UserNotFoundException ex) {
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "User does not exist");
}
}
}

1. API DOCS

NOTE: Download chrome JSON formatter to get formatted data

info:

"info": {
"description":"Api Documentation",
"version":"1.0",
"title":"Api Documentation",
"termsOfService":"urn:tos",
"contact":{...},
"license":{
"name":"Apache 2.0",
"url":"http://www.apache.org/licenses/LICENSE-2.0"
}
}

host :

"host": "localhost:8080"

basePath :

"basePath": "/"

tags:

"tags": [
{
"name":"user-controller",
"description":"User Controller"
},
{
"name":"basic-error-controller",
"description":"Basic Error Controller"
}
]

paths:

"paths": {
"/error": {...},
"/users": {...},
"/users/{id}": {...}
}
{
"/users":{
"get":{
"tags":[
"user-controller"
],
"summary":"retreiveAllUsers",
"operationId":"retreiveAllUsersUsingGET",
"consumes":[
"application/json"
],
"produces":[
"application/xml",
"application/json"
],
"responses":{
"200":{
"description":"OK",
"schema":{
"type":"array",
"items":{
"$ref":"#/definitions/User"
}
}
},
"401":{
"description":"Unauthorized"
},
"403":{
"description":"Forbidden"
},
"404":{
"description":"Not Found"
}
}
}
}
}

definitions :

"definitions":{
"User":{
"type":"object",
"properties":{
"birthDate":{
"type":"string",
"format":"date-time"
},
"id":{
"type":"integer",
"format":"int32"
},
"name":{
"type":"string"
}
}
},
"description":"User description"
}

2. SWAGGER-UI

Advanced Configuration.

@Configuration
@EnableSwagger2
public class SwaggerConfig {
public static final Contact DEFAULT_CONTACT =
new Contact("Rohan Aggarwal",
"https://github.com/xebiarohan",
"aggarwal.rohan17@gmail.com");
private static final ApiInfo DEFAULT_API_INFO =
new ApiInfo("Interesting title",
"Interesting description",
"1.0",
"urn:tos",
DEFAULT_CONTACT,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0");

private static final Set<String> DEFAULT_PRODUCES_AND_CONSUMES =
new HashSet<>(Arrays.asList("application/xml",
"application/json"));
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(DEFAULT_API_INFO)
.produces(DEFAULT_PRODUCES_AND_CONSUMES)
.consumes(DEFAULT_PRODUCES_AND_CONSUMES);
}
}
  1. Overriding the default information.
  2. Setting new “produces” configuration
  3. Setting a new “consumes” configuration.

POJO validations

@ApiModel(description = "User description")
public class User {
private Integer id;@Size(min = 2,max = 4)
@ApiModelProperty(notes="Name should be of minimum 2 characters")
private String name;
@Past
@ApiModelProperty(notes = "Birth date should be in past")
private Date birthDate;
public User() {
}
public User(Integer id, String name, Date birthDate) {
this.id = id;
this.name = name;
this.birthDate = birthDate;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", birthDate=" + birthDate +
'}';
}
}

--

--

--

Full stack developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Introducing: Torch

A Hack for Using Multiprocessing with Lambda Function in Python

IoT: Story of Wormcon 0x01

Distributed cache problem with Apollo GraphQL server

Simplifying Junit, Mockito And PowerMock

Which data type would you choose for storing currency values like Trading Price?

Why Security Engineer Need “Shift-Left” to DevSecOps?

Learning C++ using Google Colab

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Rohan Aggarwal

Rohan Aggarwal

Full stack developer

More from Medium

Unary Operator and loops in Java

Version Controlling and NoSql

Inversion of Control & Dependency Injection

You should always do server-side validation! Always!