How to create documentation with Swagger
The blog discusses the importance of documenting RESTful web services and introduces Swagger as a powerful tool for creating, documenting, and visualizing REST APIs. It covers topics such as API evolution, integration with Spring Boot, Maven dependency, and customizing Swagger documentation using annotations.
In recent years, RESTful web services have gained significant popularity and have become the dominant choice in the web services industry. They have surpassed their more complex counterpart, XML or SOAP, and are now the go-to option for API design and development. An API can be thought of as an agreement between the publisher and consumers to ensure effective communication between the two. This agreement, or contract, outlines the expectations and rules that both parties must follow. Just like any other contract, an API must be well documented to function as expected. This documentation should include details such as
- the available endpoints,
- the types of operations supported by each endpoint,
- the expected input format for an operation, and
- the format of the response that will be returned for a given request.
To keep up with changing needs, APIs must evolve over time. In this context, proper documentation is not optional, but rather a crucial aspect of the API's offerings, aimed at providing a better user experience. All this is great, but one question arises and that is how should we document for these API's, And the answer is Swagger,
Alternatives to Swagger
- Postman : A widely used API development tool that facilitates testing, documenting and sharing of APIs by developers. You can read more about it on https://learning.postman.com/docs/publishing-your-api/documenting-your-api/
- RAML : RESTful API Modeling Language (RAML) is a simple, human-friendly language for describing REST APIs. you can find more information about RAML on https://raml.org/developers/document-your-api
- ReDoc : A simple and customizable API documentation tool. You can read about ReDoc over here https://nordicapis.com/using-redoc-to-auto-generate-openapi-documentation/
What is Swagger?
So Swagger is essentially an open-source toolkit that aids in the creation, documentation, and usage of REST APIs, Swagger’s capability to provide API the power to self describe its underlying structure, is what makes it more awesome and tremendously popular.
In this article, we will Create a Rest Application and explore the process of documenting Rest APIs and visualizing it through swagger.
At first, we will integrate Swagger into a Spring Boot application that performs basic Create, Read, Update, and Delete operations for Employees.
If you plan to implement Swagger for APIs you’ve, It’s necessary to first add a maven dependency.
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>How should we configure it?
To enable Swagger we need to implement a Configuration Class.
@Configuration
public class SwaggerConfiguration {
private ApiInfo apiInfo() {
return new ApiInfo("REST APIs",
"REST APIs for CRUD Application",
"1.0",
"",
new Contact("coditation", "www.coditation.com", "coditation@gmail.com"),
"License of API",
"API license URL",
Collections.emptyList());
}
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
As you can see we have described general Information about our Rest API’s, in function apiInfo(), After this step, when we run the application we will be able to generate JSON representation of our documentation.
{
"swagger": "2.0",
"info": {
"description": "REST APIs for CRUD Application",
"version": "1.0"
"title": "REST APIs",
"contact": {
"name":"coditation"
"url": "www.coditation.com"
"email": "coditation@gmail.com"
}.
"license": {
"name": "License of API"
"url": "API license URL"
},
"host": "localhost:8080",
"basePath": "/",
"tags": [
{
"name": "basic-error-controller",
"description": "Basic Error Controller"
],
{
"name": "employee-controller"
"description": "Employee Controller"
}
],
"paths": {
"/api/v1/employees": {
"get": {
"tags": [
"employee-controller"
],
"summary": "getAllEmployees"
"operationId": "getAllEmployeesUsingGET"
"produces": [
"*/*"
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"Sref":"#/definitions/Employee"
}
Swagger UI: to see detail and to validate
Swagger provides an in built UI tool , so that you can interact with your documentation much easily
———————————————————————————————————————
Please note: you can only see above link if Swagger is configured correctly
———————————————————————————————————————

Customizing Swagger Documentation
Swagger provides us the flexibility to customize the generated REST documentation according to our needs. to customize the documentation we will need to use some swagger annotations with your functions in the controller.
Some Important Swagger Annotations are as follows :
- @ApiModel - Can be used to customize information about Model Class.
- @ApiModelProperty - Can be used to provide Extra information about Fields in Model Class.
- @ApiResponse - Provides with the Response of particular API
- @ApiOperation - Can be used to provides additional information about API
- @ApiParam - Can be used to get information about parameters used in API
Swagger Annotations In Action
@ApiOperation(value = "Get particular Employee using this API")
@ApiResponse(code = 200, message = "The Response is Retrived Successfully")
@GetMapping("/employees/{id}")
public ResponseEntity<Employee> getEmployeeById(@ApiParam(value = "EmployeeId",
required = true, defaultValue = "44") @PathVariable(value = "id") Long employeeId)
throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));
return ResponseEntity.ok().body(employee);
}Incorporating @ApiOperation, @ApiResponse & @ApiParam with your code provides you with following documentation , where we can see customized information is being displayed with associated API

On the other hand if we use @ApiModel & @ApiModelProperty annotations
@Entity
@Table(name = "employees")
@ApiModel(value = "EmployeeTable", description = "Additional information about table")
public class Employee {
@ApiModelProperty(value = "EmployeeId", required = true)
private long id;
@ApiModelProperty(value = "EmployeeFirstName")
private String firstName;
@ApiModelProperty(value = "EmployeeLastName")
private String lastName;
@ApiModelProperty(value = "EmailId")
private String emailId;
We will get following output about our Model Class from Swagger

As you can see all properties in model class has description associated with it and also the mandatory field has * associated with it.
Conclusion
Swagger is a powerful tool that compliments your API’s. It offers complete flexibility in automating the documentation process for API’s, and it will be very helpful for the new software engineers that would be joining your team to understand the API structure very clearly and rapidly.
JSON
{
"swagger": "2.0",
"info": {
"description": "REST APIs for CRUD Application",
"version": "1.0",
"title": "REST APIs",
"contact": {
"name": "coditation",
"url": "www.coditation.com",
"email": "coditation@gmail.com"
},
"license": {
"name": "License of API",
"url": "API license URL"
}
},
"host": "localhost:8080",
"basePath": "/",
"tags": [
{
"name": "basic-error-controller",
"description": "Basic Error Controller"
},
{
"name": "employee-controller",
"description": "Employee Controller"
}
],
"paths": {
"/api/v1/employees": {
"get": {
"tags": [
"employee-controller"
],
"summary": "Get all Employees with this REST API",
"operationId": "getAllEmployeesUsingGET",
"produces": [
"*/*"
],
"responses": {
"200": {
"description": "All Employees Retrived Successfully",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/EmployeeTable"
}
}
},
"401": {
"description": "Unauthorized"
},
"403": {
"description": "Forbidden"
},
"404": {
"description": "Not Found"
}
}
},
"post": {
"tags": [
"employee-controller"
],
"summary": "createEmployee",
"operationId": "createEmployeeUsingPOST",
"consumes": [
"application/json"
],
"produces": [
"*/*"
],
"parameters": [
{
"in": "body",
"name": "employee",
"description": "employee",
"required": true,
"schema": {
"$ref": "#/definitions/EmployeeTable"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/EmployeeTable"
}
},
"201": {
"description": "Created"
},
"401": {
"description": "Unauthorized"
},
"403": {
"description": "Forbidden"
},
"404": {
"description": "Not Found"
}
}
}
},
"/api/v1/employees/{id}": {
"get": {
"tags": [
"employee-controller"
],
"summary": "Get particular Employee using this API",
"operationId": "getEmployeeByIdUsingGET",
"produces": [
"*/*"
],
"parameters": [
{
"name": "id",
"in": "path",
"description": "EmployeeId",
"required": true,
"type": "integer",
"default": 44,
"format": "int64"
}
],
"responses": {
"200": {
"description": "The Response is Retrived Successfully",
"schema": {
"$ref": "#/definitions/EmployeeTable"
}
},
"401": {
"description": "Unauthorized"
},
"403": {
"description": "Forbidden"
},
"404": {
"description": "Not Found"
}
}
},
"put": {
"tags": [
"employee-controller"
],
"summary": "updateEmployee",
"operationId": "updateEmployeeUsingPUT",
"consumes": [
"application/json"
],
"produces": [
"*/*"
],
"parameters": [
{
"in": "body",
"name": "employeeDetails",
"description": "employeeDetails",
"required": true,
"schema": {
"$ref": "#/definitions/EmployeeTable"
}
},
{
"name": "id",
"in": "path",
"description": "id",
"required": true,
"type": "integer",
"format": "int64"
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/EmployeeTable"
}
},
"201": {
"description": "Created"
},
"401": {
"description": "Unauthorized"
},
"403": {
"description": "Forbidden"
},
"404": {
"description": "Not Found"
}
}
},





