Swagger Documentation with Spring Boot

๐Ÿ“˜ What is Swagger?

Swagger (OpenAPI) is a tool that automatically generates interactive API documentation for your REST endpoints โ€” making it easier to test, share, and understand your APIs.


๐Ÿš€ Quickstart: Swagger with Spring Boot

โœ… Step 1: Add Swagger Dependencies (OpenAPI 3)

In pom.xml:

<dependency>
ย  ย  <groupId>org.springdoc</groupId>
ย  ย  <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
ย  ย  <version>2.5.0</version> <!-- Check for latest -->
</dependency>

โœ… Step 2: Run Your App

Once the dependency is added and your Spring Boot app is running, visit:

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

or

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

Youโ€™ll see an interactive page listing all your REST endpoints! ๐ŸŽ‰


โœ… Step 3: Optional API Info (Customization)

You can customize the Swagger info using annotations:

@OpenAPIDefinition(
ย  ย  info = @Info(
ย  ย  ย  ย  title = "Student API",
ย  ย  ย  ย  version = "1.0",
ย  ย  ย  ย  description = "API for managing students"
ย  ย  )
)
@SpringBootApplication
public class MyApp {
ย  ย  public static void main(String[] args) {
ย  ย  ย  ย  SpringApplication.run(MyApp.class, args);
ย  ย  }
}

๐Ÿง‘๐Ÿ’ป Example REST Controller

@RestController
@RequestMapping("/students")
public class StudentController {

ย  ย  @GetMapping("/{id}")
ย  ย  public ResponseEntity<Student> getStudent(@PathVariable Long id) {
ย  ย  ย  ย  return ResponseEntity.ok(new Student(id, "Aftab", "aftab@email.com"));
ย  ย  }

ย  ย  @PostMapping
ย  ย  public ResponseEntity<String> createStudent(@RequestBody Student student) {
ย  ย  ย  ย  return ResponseEntity.ok("Student created!");
ย  ย  }
}

ย 

These will appear automatically in Swagger UI.


๐Ÿง  Why Use Swagger?

  • ๐Ÿ“– Auto-generated API documentation
  • ๐Ÿงช Try out API endpoints directly from the browser
  • ๐Ÿ“ค Easy to share with frontend/mobile teams
  • โœ… Great for debugging and testing
Back to blog

Leave a comment