Swagger Overview
Swagger is an open-source framework that simplifies API documentation by generating interactive, machine-readable specifications from code annotations. It enables frontend and backend teams to collaborate efficiently by providing real-time API documentation and a built-in testing interface.
Project Setup
Maven Dependencies
Add the following dependencies to your pom.xml file:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
Basic Controller Example
Create a simple REST controller:
@RestController
public class SampleController {
@ResponseBody
@RequestMapping(value = "/greet", method = RequestMethod.GET)
public String sayHello() {
return "Hello World";
}
}
Swagger Configuration
Enabling Swagger
Create a configuration class to enable Swagger support:
import org.springframework.context.annotation.Configuration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
}
@Configurationregisters the class as a Spring bean@EnableSwagger2activates Swagger 2 functionality
After starting the application, access the Swagger UI at: http://localhost:8080/swagger-ui.html
The interface displays:
- API documentation header information
- Available endpoints grouped by controllers
- Model definitions
Customizing Documentation
Configuring API Metadata
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
import java.util.Arrays;
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
private Contact createContact() {
return new Contact("Developer Name", "https://example.com", "dev@example.com");
}
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(metadata())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
.build();
}
private ApiInfo metadata() {
return new ApiInfo(
"Sample API",
"API documentation for the sample application",
"1.0.0",
"https://example.com/terms",
createContact(),
"Apache 2.0 License",
"https://www.apache.org/licenses/LICENSE-2.0",
Arrays.asList()
);
}
}
API Selector Options
The apis() method controls which endpoints are documented:
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
Available options:
basePackage("package")- Scan specific packageany()- Include all endpointsnone()- Exclude all endpointswithClassAnnotation(Annotation.class)- Include based on class annotationswithMethodAnnotation(Annotation.class)- Include based on method annotations
Path Filtering
Control which paths are exposed:
.paths(PathSelectors.ant("/api/**"))
Options include:
ant(String pattern)- Ant-style path patternany()- Include all pathsnone()- Exclude all pathsregex(String regex)- Regular expression matching
Environment-Specific Configuraton
Enable Swagger only for specific environments:
@Bean
public Docket api(Environment environment) {
Profiles activeProfiles = Profiles.of("dev", "test");
boolean isEnabled = environment.acceptsProfiles(activeProfiles);
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(metadata())
.enable(isEnabled)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
.build();
}
The enable(false) method disables Swagger documentation. This is recommended for production environments.
API Grouping
Create multiple Docket beans to generate separate documentation groups:
@Bean
public Docket adminApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(metadata())
.groupName("Admin Endpoints")
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.admin"))
.build();
}
@Bean
public Docket userApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(metadata())
.groupName("User Endpoints")
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.user"))
.build();
}
The Swagger UI displays a dropdown selector to switch between difefrent API groups.
Model Documentation
Documenting Response Entities
Include model classes in the API documentation:
@PostMapping(value = "/users")
public UserEntity getUser() {
return new UserEntity();
}
Ensure entity classes have proper getter and setter methods.
Adding Annotations
Use Swagger annotations to provide descriptive information:
@ApiModel(description = "User account information")
public class UserEntity {
@ApiModelProperty(value = "Unique username identifier")
private String username;
@ApiModelProperty(value = "User email address")
private String email;
// getters and setters
}
For controller methods:
@ApiOperation(value = "Retrieve user by name", notes = "Returns user details for the specified username")
@GetMapping(value = "/users/{name}")
public UserEntity findUser(@ApiParam(value = "Username to search for", required = true) @PathVariable String name) {
return new UserEntity();
}
Key annotations:
@ApiModel- Describes a model class@ApiModelProperty- Documents model properties@ApiOperation- Describes an endpoint@ApiParam- Documents method parameters
Swagger automatically generates interactive documentation with these annotations. The built-in "Try it out" feature allows testing endpoints directly from the browser.