Java

Chapter 146: Swagger/OpenAPI in Java — Contracts, springdoc-ui, and Generated Clients

Document and exercise Java APIs with OpenAPI 3: YAML vs annotations, springdoc-openapi with Spring Boot, Swagger UI for try-it-out, and generating clients or server stubs from the spec.

Author: Sushil Kumar

Java OpenAPI Spring BootJava springdoc swaggerJava Swagger UI RESTOpenAPI 3 Java contractJava API documentation OpenAPI

Chapter 146: Swagger/OpenAPI in Java

OpenAPI (formerly Swagger spec) describes paths, parameters, request bodies, responses, and security schemes in YAML or JSON. springdoc-openapi auto-generates a spec from Spring MVC annotations and serves Swagger UI for interactive trials.


1. Topic title

OpenAPI: single contract for docs, tests, gateways, and client SDK generation


2. What it means

openapi: 3.0.x document lists servers, paths./items.get, components.schemas.Itemmachines and humans share it.

Annotations (@Operation, @Parameter) refine generated docs when defaults are vague.

Codegen produces Java clients or server interfacesCI can fail when spec drifts.


3. Why it is used

Onboardingnew developers explore APIs without reading all controllers.

Consumer-driven contractspublish spec to portal versioned with API.


4. Mental sketch

OpenAPI is the sheet music for your HTTP orchestraconductors (gateways), players (services), and audience (SDK users) read the same score.


5. Java code example

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
@Tag(name = "Hello")
public class OpenApiHelloController {
    @GetMapping("/api/hello")
    @Operation(summary = "Returns greeting")
    public String hello() {
        return "hello";
    }
}

Requires springdoc-openapi-starter-webmvc-ui dependency—visit /swagger-ui.html after bootRun.


6. Explanation of code

springdoc groups beans by tagsmirror bounded contexts in tag names.


7. Common mistakes

Shipping UI in prod without authSwagger UI can invoke real mutationsprotect or disable.

Spec lyingannotations out of sync with real validationtreat spec as code in review.


8. Best practices

Publish openapi.yaml as build artifactdiff on PRs.

Example payloads for 4xx responses help clients branch UI.


9. Small practice task

Add @Schema descriptions to a DTO field and reload Swagger UIconfirm text appears.


Beginner tip

OpenAPI ≠ implementationintegration tests still prove behavior; docs describe intent.