How to Use Swagger with Spring Boot: Simple Setup Guide
To use
Swagger with Spring Boot, add the springdoc-openapi-ui dependency to your project and configure your application. This automatically generates interactive API docs accessible via /swagger-ui/index.html.Syntax
To enable Swagger UI in Spring Boot, add the springdoc-openapi-ui dependency in your pom.xml or build.gradle. Then, annotate your REST controllers with @RestController and use standard Spring MVC annotations like @GetMapping. Swagger UI will auto-generate documentation from these.
xml
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.7.0</version>
</dependency>Example
This example shows a simple Spring Boot REST controller with Swagger UI enabled. After running, visit http://localhost:8080/swagger-ui/index.html to see the interactive API docs.
java
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication public class SwaggerDemoApplication { public static void main(String[] args) { SpringApplication.run(SwaggerDemoApplication.class, args); } } @RestController class HelloController { @GetMapping("/hello") public String sayHello() { return "Hello, Swagger!"; } }
Output
Spring Boot app starts on port 8080; Swagger UI available at /swagger-ui/index.html showing /hello endpoint.
Common Pitfalls
- Not adding the
springdoc-openapi-uidependency or using an outdated version. - Trying to access Swagger UI at
/swagger-ui.htmlinstead of/swagger-ui/index.htmlin recent versions. - Missing
@RestControlleror mapping annotations on your API methods. - Conflicts with Spring Security blocking access to Swagger endpoints.
java
/* Wrong: Missing dependency, Swagger UI won't load */ // No springdoc-openapi-ui dependency in pom.xml /* Right: Add dependency and use correct URL */ // Add springdoc-openapi-ui dependency // Access Swagger UI at /swagger-ui/index.html
Quick Reference
| Step | Description |
|---|---|
| 1 | Add springdoc-openapi-ui dependency (version 1.7.0 or later) |
| 2 | Annotate your REST controllers with @RestController and mapping annotations |
| 3 | Run your Spring Boot app |
| 4 | Open http://localhost:8080/swagger-ui/index.html in a browser |
| 5 | Use Swagger UI to explore and test your API endpoints |
Key Takeaways
Add the springdoc-openapi-ui dependency to enable Swagger UI in Spring Boot.
Annotate your REST controllers properly for Swagger to generate docs automatically.
Access Swagger UI at /swagger-ui/index.html, not /swagger-ui.html in recent versions.
Check Spring Security settings if Swagger UI is not accessible.
Use the latest springdoc-openapi version for best compatibility and features.