Spring Boot Swagger UI and OpenAPI 3 Tutorial: Document REST APIs

  

Spring Boot Swagger UI and OpenAPI 3 Tutorial

Introduction

Building a REST API is only one part of developing a professional application.

Once an API contains many endpoints, developers need an easy way to understand:

  • Available endpoints
  • HTTP methods
  • Request parameters
  • Request bodies
  • Response formats
  • Authentication requirements
  • Error responses

This is where OpenAPI and Swagger UI become useful.

OpenAPI provides a standardized description of an HTTP API, while Swagger UI provides an interactive web interface for exploring and testing that API.

For Spring Boot applications, springdoc-openapi can automatically generate OpenAPI documentation from your application's Spring configuration, controllers, and annotations.

In this tutorial, we'll build Swagger/OpenAPI documentation for a Spring Boot REST API.


What is OpenAPI?

OpenAPI is a specification for describing HTTP APIs.

An OpenAPI document can describe:

  • API endpoints
  • HTTP methods
  • Parameters
  • Request bodies
  • Responses
  • Authentication
  • Data models

For example, an API might contain:

GET /api/employees
GET /api/employees/{id}
POST /api/employees
PUT /api/employees/{id}
DELETE /api/employees/{id}

OpenAPI allows these endpoints to be described in a machine-readable format.


What is Swagger?

Swagger is a collection of tools associated with working with OpenAPI.

One of the most popular tools is Swagger UI.

Swagger UI turns an OpenAPI definition into an interactive web page where developers can:

  • Browse API endpoints
  • Read endpoint descriptions
  • View request parameters
  • View response schemas
  • Send requests
  • Test API endpoints

The important distinction is:

OpenAPI
API Description / Specification
Swagger UI
Interactive Documentation

Why Use Swagger UI with Spring Boot?

Without API documentation, a developer might need to read controller source code to understand an API.

With Swagger UI:

Developer
Swagger UI
API Endpoints
Request / Response Information
Try API

This can make development and API testing much easier.


Spring Boot OpenAPI Architecture

Spring Boot Application
REST Controllers
springdoc-openapi
OpenAPI Document
┌──────────┴──────────┐
↓ ↓
/v3/api-docs Swagger UI
Interactive API Docs

Add the OpenAPI Dependency

For a Spring MVC application, springdoc-openapi-starter-webmvc-ui integrates OpenAPI documentation with Swagger UI. The springdoc project documents this starter for Spring Boot 3.x and provides Swagger UI plus the generated /v3/api-docs endpoint.

Add this dependency to your pom.xml:

<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>3.0.3</version>
</dependency>

Important: springdoc has separate compatibility lines for different Spring Boot generations. The current springdoc project lists version 3.0.3 as its latest release, while its documentation specifically notes that springdoc v2 supports Spring Boot 3.x. Therefore, if your project is still using Spring Boot 3, use the compatible springdoc 2.x release rather than blindly copying the 3.x dependency above.

For the Spring Boot 3 tutorials on your site, I recommend using the Spring Boot 3-compatible springdoc release consistently.


Start the Application

After adding the dependency, start your Spring Boot application.

If your application runs on:

http://localhost:8080

springdoc generates the OpenAPI JSON document at:

http://localhost:8080/v3/api-docs

The springdoc documentation identifies /v3/api-docs as the default JSON OpenAPI endpoint.


Open Swagger UI

Swagger UI can be accessed through the generated Swagger interface.

Depending on the configuration and springdoc version, the UI is available at:

http://localhost:8080/swagger-ui.html

or:

http://localhost:8080/swagger-ui/index.html

The springdoc project documents Swagger UI as being automatically deployed when the UI starter is included.


Create a REST Controller

Let's use an employee API.

@RestController
@RequestMapping("/api/employees")
public class EmployeeController {

@GetMapping
public List<Employee> getEmployees() {

return employeeService.getEmployees();
}

@GetMapping("/{id}")
public Employee getEmployee(
@PathVariable Long id) {

return employeeService
.getEmployee(id);
}

@PostMapping
public Employee createEmployee(
@RequestBody Employee employee) {

return employeeService
.saveEmployee(employee);
}
}

Once the application starts, springdoc can inspect the application's API structure and generate documentation.


View the Generated OpenAPI Document

Open:

/v3/api-docs

You will receive an OpenAPI document containing information about the API.

A simplified example looks like:

{
"openapi": "3.0.1",
"paths": {
"/api/employees": {
"get": {
"summary": "Get employees"
}
}
}
}

The actual generated document will contain significantly more information.


Improve API Documentation with Annotations

Automatic documentation is useful, but you can make it much better by adding descriptions.

For example:

@Operation(
summary = "Get all employees",
description = "Returns a list of all employees"
)
@GetMapping
public List<Employee> getEmployees() {

return employeeService
.getEmployees();
}

This gives API consumers more context.


Document an Endpoint

You can use:

@Operation

to describe an API operation.

Example:

@Operation(
summary = "Find employee by ID",
description =
"Returns an employee using the employee ID"
)
@GetMapping("/{id}")
public Employee getEmployee(
@PathVariable Long id) {

return employeeService
.getEmployee(id);
}

Document Path Parameters

For more detailed documentation:

@Parameter(
description = "Employee ID",
example = "10"
)
@PathVariable Long id

Example:

@GetMapping("/{id}")
public Employee getEmployee(

@Parameter(
description = "Employee ID",
example = "10"
)
@PathVariable Long id) {

return employeeService
.getEmployee(id);
}

Document Request Bodies

Suppose our API accepts:

{
"name": "John",
"department": "IT",
"salary": 75000
}

We can describe the request using OpenAPI annotations.

@Operation(
summary = "Create employee"
)
@PostMapping
public Employee createEmployee(
@RequestBody Employee employee) {

return employeeService
.saveEmployee(employee);
}

Document API Responses

You can also describe possible responses.

@ApiResponses({

@ApiResponse(
responseCode = "200",
description =
"Employee retrieved successfully"
),

@ApiResponse(
responseCode = "404",
description =
"Employee not found"
)

})

Example:

@GetMapping("/{id}")
@Operation(
summary = "Get employee by ID"
)
@ApiResponses({

@ApiResponse(
responseCode = "200",
description = "Employee found"
),

@ApiResponse(
responseCode = "404",
description = "Employee not found"
)

})
public Employee getEmployee(
@PathVariable Long id) {

return employeeService
.getEmployee(id);
}

This makes the Swagger documentation much more useful.


Document the API with @Tag

You can organize controllers using tags.

@Tag(
name = "Employee API",
description =
"Operations related to employees"
)
@RestController
@RequestMapping("/api/employees")
public class EmployeeController {
}

Swagger UI can then group the endpoints under:

Employee API

Add API Information

You can also provide general information about your API.

Create a configuration class:

@Configuration
public class OpenApiConfig {

@Bean
public OpenAPI customOpenAPI() {

return new OpenAPI()
.info(new Info()
.title("Employee Management API")
.version("1.0")
.description(
"REST API for managing employees"
));
}
}

This improves the information displayed in Swagger UI.


Swagger UI for CRUD APIs

Swagger becomes especially useful when you've built a CRUD application.

For example:

Employee API

GET /api/employees
GET /api/employees/{id}
POST /api/employees
PUT /api/employees/{id}
DELETE /api/employees/{id}

Developers can open Swagger UI and immediately understand the API.


Swagger UI and Request Testing

One of the biggest advantages of Swagger UI is the ability to interact with API endpoints directly from the browser.

For example:

GET /api/employees/{id}

[ Try it out ]

id: 10

[ Execute ]

Swagger UI sends the request and displays the response.

This can reduce the need to manually construct requests while developing and testing an API.


Swagger UI with JWT Authentication

Swagger becomes even more useful when an API is protected with JWT.

Because we've already created our JWT authentication tutorial, we can connect the two concepts.

The flow becomes:

User
Swagger UI
Authorize
JWT Token
Protected API
Response

You can define a bearer authentication scheme in OpenAPI.

Example:

@Bean
public OpenAPI customOpenAPI() {

return new OpenAPI()
.components(
new Components()
.addSecuritySchemes(
"bearer-key",
new SecurityScheme()
.type(
SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")
)
);
}

Then you can associate security requirements with protected operations.


Swagger vs Postman

Swagger UI and Postman serve different purposes.

Swagger UIPostman
API documentationAPI testing
Generated from OpenAPIManually created requests
Interactive documentationAdvanced request collections
Easy for API consumersPowerful testing workflows
Shows API contractExcellent for testing APIs

Many development teams use both.

OpenAPI
Swagger UI → Documentation
Postman → Testing

Swagger vs Spring REST Docs

Spring also provides Spring REST Docs, which takes a different approach to API documentation.

Spring REST Docs combines hand-written documentation with snippets generated from tests. Its test-driven approach helps keep documentation accurate because incorrect snippets can cause the generating tests to fail.

A simplified comparison:

Swagger/OpenAPISpring REST Docs
Interactive UIDocumentation-focused
OpenAPI specificationTest-generated snippets
Easy API explorationStrong accuracy through tests
Great for API consumersExcellent for test-driven documentation

Neither approach is automatically "better" for every project.


Customize Swagger UI

You can customize the Swagger UI path.

For example:

springdoc.swagger-ui.path=/api-docs

The springdoc documentation supports customizing the Swagger UI path through the springdoc.swagger-ui.path property.

You could then access:

http://localhost:8080/api-docs

Customize OpenAPI JSON Path

You can also change the generated API documentation path.

springdoc.api-docs.path=/openapi

The OpenAPI document would then be available at:

/openapi

The springdoc project documents springdoc.api-docs.path for customizing the API documentation endpoint.


Don't Expose Sensitive Information

Swagger UI is useful, but remember that API documentation can reveal your application's structure.

Avoid exposing internal information such as:

  • Database credentials
  • Secret keys
  • Passwords
  • Internal infrastructure details
  • Private administrative endpoints

Swagger documents your API; it does not automatically make your API secure.


Secure Swagger in Production

For public APIs, you need to decide whether Swagger UI should be publicly accessible.

For private APIs, you may want to require authentication.

Conceptually:

Public User
Application API

Developer/Admin
Authentication
Swagger UI
Protected API

If you're already using Spring Security, you can configure authorization rules around the documentation endpoints.


OpenAPI Documentation Architecture

REST API
Spring Controllers
springdoc-openapi
OpenAPI 3 Spec
/ \
↓ ↓
/v3/api-docs Swagger UI
API Exploration
Try It Out

Common Mistakes

Mistake 1: Documenting Only the Happy Path

Document error responses too.

For example:

200 → Success
400 → Invalid Request
401 → Unauthorized
403 → Forbidden
404 → Not Found
500 → Server Error

Mistake 2: Leaving Endpoints Undocumented

Automatic generation is helpful, but add meaningful descriptions to important APIs.


Mistake 3: Ignoring Security

Don't assume Swagger UI protects your API.

Your Spring Security configuration must still protect actual application endpoints.


Mistake 4: Exposing Internal APIs

Think carefully before publishing administrative endpoints in public API documentation.


Mistake 5: Using Outdated Dependencies

OpenAPI libraries change as Spring Boot versions evolve.

Always check the compatibility information for your Spring Boot version before selecting the springdoc release. The springdoc project maintains separate support lines for different Spring Boot generations.


Best Practices

Keep API Documentation Close to the Code

Use annotations where they improve clarity.

Document Error Responses

Consumers need to know what happens when a request fails.

Describe Request and Response Models

Don't make users guess the JSON structure.

Document Authentication

Explain whether endpoints require JWT, OAuth2, or another mechanism.

Keep Documentation Updated

An outdated API document can be worse than no documentation.

Protect Sensitive Documentation

Especially for private or internal applications.


Frequently Asked Questions

What is Swagger UI in Spring Boot?

Swagger UI is an interactive interface that displays an OpenAPI description of your Spring Boot REST API and allows users to explore and test endpoints.

What is OpenAPI?

OpenAPI is a specification for describing HTTP APIs in a machine-readable format.

What is springdoc-openapi?

springdoc-openapi is a community project that integrates OpenAPI documentation and Swagger UI with Spring Boot applications.

What is the default OpenAPI URL?

For a typical springdoc configuration, the generated JSON document is available at:

/v3/api-docs

Can Swagger UI test POST and PUT APIs?

Yes. Swagger UI can provide interactive forms for API requests when the API is appropriately described.

Can Swagger work with JWT?

Yes. OpenAPI supports security schemes, including HTTP bearer authentication, which can be used to describe JWT-protected APIs.


Conclusion

OpenAPI and Swagger UI make Spring Boot REST APIs easier to understand, test, and consume.

Instead of forcing developers to read controller source code or search through separate documentation, you can provide an interactive API reference generated from your application.

For a professional Spring Boot project, a good API documentation strategy should include:

  • Clear endpoint descriptions
  • Request examples
  • Response examples
  • Error responses
  • Authentication information
  • Data models
  • Accurate documentation
  • Appropriate production security

When combined with the REST API, CRUD, validation, exception handling, security, JWT, and testing topics we've already covered, this becomes an important part of building a complete Spring Boot development knowledge base.


Continue Learning Spring Boot

Muhammad Zeeshan Haider

Hello, I'm Muhammad Zeeshan, a Java Developer, Spring Boot Educator, and Technical Blogger. Through Java Web Action, I share practical tutorials, guides, and real-world examples on Java, Spring Boot, Microservices, REST APIs, JPA, Hibernate, MySQL, and software architecture. My goal is to help developers learn modern Java technologies and build professional applications with confidence.

Post a Comment

Please enter relevant questions and information.

Previous Post Next Post