EthicsComputerCourses
Join training +91 90532 10052

API Docs with OpenAPI

Spring Boot + React · Lesson 8 of 20 Intermediate 11 min read Updated

By the end of this lesson the StaffDesk API will describe itself. springdoc-openapi will build an OpenAPI document from your controllers and records, Swagger UI will let you try every endpoint with a JWT, and the React team will have a contract file they can read, review and even use in code.

What you should know first: Spring Security with JWT, because the docs must pass through the security rules, and Validation & Error Handling for the error shape we document. For controllers and records in general, see Request & Response Bodies. Versions checked on 16 November 2026: springdoc-openapi 3.2.0 (released 24 October 2026, built against Spring Boot 4.1.2), which bundles Swagger UI 5.34.0.

Why a machine-readable contract

So far the StaffDesk contract lives in a Markdown table in the README. Tables go out of date quietly. Someone adds a field to EmployeeResponse and forgets the table, and the React developer finds out from a bug.

OpenAPI is a standard format (JSON or YAML) for describing an HTTP API: its paths, methods, parameters, request and response bodies, status codes and security. Think of it as the railway timetable printed by the railway itself, instead of a list a passenger copied by hand. springdoc-openapi is a library that reads your Spring MVC controllers, records and validation annotations at run time and writes that timetable for you. Swagger UI is a web page that shows the document and lets you send real requests from the browser.

springdoc-openapiFor Spring Boot
3.x4.x
2.x3.x
1.8.0 (end of open-source support)2.x and 1.x

That table comes from the project's README. Using a 2.x version with Spring Boot 4 is a common mistake after an upgrade.

Step 1: Add the starter

Add one dependency to backend/pom.xml. Spring Boot does not manage springdoc's version, so you write it yourself:

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

Restart the API and ask for the document:

Terminal
curl -i http://localhost:8080/v3/api-docs
Output
HTTP/1.1 401
WWW-Authenticate: Bearer resource_metadata="http://localhost:8080/.well-known/oauth-protected-resource"
Content-Length: 0

Good news, in a way: the security rules from the last lesson work. Every path that is not listed is authenticated(), and the docs are not listed.

Step 2: Let the docs through, in development only

Add the springdoc paths to the public rules in SecurityConfig:

Java
.requestMatchers(HttpMethod.POST, "/api/auth/login").permitAll()
.requestMatchers("/v3/api-docs/**", "/v3/api-docs.yaml", "/swagger-ui/**",
        "/swagger-ui.html").permitAll()
.requestMatchers("/api/employees/**").hasRole("HR")

The .yaml line is not decoration. Our first try had only /v3/api-docs/**; the JSON worked but /v3/api-docs.yaml still returned 401, because /** matches path segments after a slash, not a different file name.

An API description is a map for attackers too. Production StaffDesk switches it off in application-prod.properties:

Properties
# No interactive API docs on the production server
springdoc.api-docs.enabled=false
springdoc.swagger-ui.enabled=false

Both property names are listed in springdoc's configuration metadata. Publish the contract file instead (Step 6), so the team still has it.

Step 3: Describe the API and its security

Without help, springdoc calls the API "OpenAPI definition" and knows nothing about the JWT. Add one configuration class:

Java
package in.staffdesk.api.config;

@Configuration
public class OpenApiConfig {

    public static final String BEARER = "bearerAuth";

    @Bean
    OpenAPI staffDeskOpenApi() {
        return new OpenAPI()
                .info(new Info()
                        .title("StaffDesk API")
                        .version("1.0")
                        .description("Employee directory for the Gurugram office. "
                                + "Errors use RFC 9457 problem details."))
                .components(new Components().addSecuritySchemes(BEARER,
                        new SecurityScheme()
                                .type(SecurityScheme.Type.HTTP)
                                .scheme("bearer")
                                .bearerFormat("JWT")));
    }
}

The classes come from io.swagger.v3.oas.models, which the starter brings in. A security scheme tells tools how to authenticate: here, an HTTP Authorization: Bearer header carrying a JWT, which matches the choice made in the security lesson.

Two settings go in application.properties:

Properties
# API docs (springdoc-openapi)
springdoc.default-produces-media-type=application/json
springdoc.swagger-ui.operations-sorter=method

The first fixes a small surprise. Our controllers do not say what they produce, so springdoc first listed every response as */* (any type). The second sorts operations by HTTP method in Swagger UI.

Step 4: Describe the endpoints

springdoc already knows paths, parameters and body shapes. Annotations add what code cannot say: summaries, extra status codes and which operations need a token. In EmployeeController:

Java
@Tag(name = "Employees", description = "The StaffDesk employee directory")
@RestController
@RequestMapping("/api/employees")
public class EmployeeController {

    @Operation(summary = "Add an employee (HR only)")
    @SecurityRequirement(name = OpenApiConfig.BEARER)
    @ApiResponse(responseCode = "201", description = "Created; Location holds the new URL")
    @ApiResponse(responseCode = "400", description = "Invalid fields",
            content = @Content(mediaType = "application/problem+json",
                    schema = @Schema(implementation = ProblemDetail.class)))
    @ApiResponse(responseCode = "409", description = "Email already used",
            content = @Content(mediaType = "application/problem+json",
                    schema = @Schema(implementation = ProblemDetail.class)))
    @PostMapping
    public ResponseEntity<EmployeeResponse> create(@Valid @RequestBody EmployeeRequest request) {
        // unchanged
    }
}

list, get, update and delete get one-line @Operation summaries; update and delete also get @SecurityRequirement, and get and delete declare 404 with content = @Content (meaning "no body"), which is exactly what the contract says. AuthController gets @Tag(name = "Auth"). The annotations live in io.swagger.v3.oas.annotations; they describe the API but change nothing about how it runs.

Now fetch the YAML version. These lines are from our run:

Terminal
curl http://localhost:8080/v3/api-docs.yaml
Output
openapi: 3.1.0
info:
  title: StaffDesk API
  description: Employee directory for the Gurugram office. Errors use RFC 9457 problem
    details.
  version: "1.0"
servers:
- url: http://localhost:8080
  description: Generated server url
tags:
- name: Auth
  description: Log in and check who you are
- name: Employees
  description: The StaffDesk employee directory

Further down, the request record appears as a schema. Look closely: nobody wrote this by hand.

Output
EmployeeRequest:
  type: object
  properties:
    fullName:
      type: string
      maxLength: 80
      minLength: 0
    email:
      type: string
      format: email
      maxLength: 120
      minLength: 0
    designation:
      type: string
      maxLength: 60
      minLength: 0
    departmentId:
      type: integer
      format: int64
    joinedOn:
      type: string
      format: date
  required:
  - departmentId
  - designation
  - email
  - fullName
  - joinedOn

springdoc turned @NotBlank and @NotNull into required, @Size(max = 80) into maxLength, @Email into format: email and LocalDate into format: date. The @Positive on the departmentId query parameter became exclusiveMinimum: 0. The Bean Validation annotations from the validation lesson are now part of the published contract, so the server rules and the documented rules cannot drift apart. The document also listed eight schemas, including ProblemDetail, LoginRequest and LoginResponse.

Step 5: Try it in Swagger UI

Open http://localhost:8080/swagger-ui.html; it redirects to /swagger-ui/index.html. In headless Chrome the page showed the title "StaffDesk API 1.0", an "OAS 3.1" badge, an Authorize button, and four groups: "Auth", "Employees", "status-controller" and "department-controller". Controllers without @Tag get those generated names. Under Employees it listed DELETE, GET, GET, POST, PUT with summaries such as "Add an employee (HR only)", and a Schemas section listed all eight records.

To call a protected endpoint from the page:

  1. Open POST /api/auth/login, click Try it out, enter Priya's email and password, and Execute.
  2. Copy the token value from the response body (without quotes).
  3. Click Authorize, paste the token into the bearerAuth box, and close the dialog.
  4. Open POST /api/employees, Try it out, fill the example body and Execute. Swagger UI now adds the Authorization header; operations with a lock icon use it.

Try the same with Aarav's token and you will see the 403 from the security lesson. Swagger UI is a fast way for testers and the React team to explore the API, but it calls the real server: on a shared test server, those are real changes.

Step 6: Keep the contract in Git

Save the document next to the code and commit it:

Terminal
mkdir -p docs
curl -s http://localhost:8080/v3/api-docs.yaml -o docs/openapi.yaml
git diff --stat docs/openapi.yaml

Now every pull request that changes the API also changes docs/openapi.yaml, and reviewers see the contract change line by line. A renamed JSON key shows up as a red line and a green line, before React breaks. springdoc also offers a Maven plugin that writes the file during the build, which suits CI; see the plugins page linked from springdoc.org.

The front end can read the same contract. The example below holds the EmployeeRequest schema exactly as our API produced it, and uses its required list and maxLength values to set the HTML form limits, so the form and the server cannot disagree. The server still checks everything.

React JSXOpen in editor
import { createRoot } from "react-dom/client";

// The EmployeeRequest schema from StaffDesk's /v3/api-docs
const schema = {
  type: "object",
  properties: {
    fullName: { type: "string", maxLength: 80, minLength: 0 },
    email: { type: "string", format: "email", maxLength: 120, minLength: 0 },
    designation: { type: "string", maxLength: 60, minLength: 0 },
    departmentId: { type: "integer", format: "int64" },
    joinedOn: { type: "string", format: "date" },
  },
  required: ["departmentId", "designation", "email", "fullName", "joinedOn"],
};

const labels = { fullName: "Full name", email: "Work email", designation: "Designation", departmentId: "Department id", joinedOn: "Joined on" };
const inputType = (p) => p.format === "email" ? "email" : p.format === "date" ? "date" : p.type === "integer" ? "number" : "text";

function App() {
  const fields = Object.entries(schema.properties);
  fields.forEach(([name, p]) => console.log(name, inputType(p), p.maxLength ?? "-"));
  return (
    <form style={{ fontFamily: "system-ui, sans-serif" }} onSubmit={(e) => e.preventDefault()}>
      <h1>Add employee (built from the contract)</h1>
      {fields.map(([name, p]) => (
        <p key={name}>
          <label htmlFor={name}>{labels[name]}{schema.required.includes(name) ? " *" : ""}</label><br />
          <input id={name} name={name} type={inputType(p)} maxLength={p.maxLength}
            required={schema.required.includes(name)} />
        </p>
      ))}
      <button type="submit">Save</button>
    </form>
  );
}

createRoot(document.getElementById("root")).render(<App />);

You see five labelled fields, each marked with *, and the console lists each field's input type and limit: fullName text 80, email email 120, designation text 60, departmentId number -, joinedOn date -. Type more than 80 characters into "Full name" and the browser stops you. Change maxLength: 80 to 20 and run it again: the form follows the contract.

Common mistakes

  • springdoc 2.x on Spring Boot 4. Use the 3.x line for Boot 4.
  • Docs blocked by security, then fixed with anyRequest().permitAll(). Open only the doc paths, and only outside production.
  • Swagger UI on the public production server. It advertises every endpoint. Disable it with the prod profile and share the YAML file.
  • Documenting only the happy path. React needs 400, 401, 403, 404 and 409 as much as 200.
  • Hand-written docs next to generated ones. Two sources of truth drift apart. Let the code generate the document and review it in Git.

Interview questions

1. What is the difference between OpenAPI and Swagger?

OpenAPI is the specification for describing HTTP APIs; it grew out of the Swagger specification, which was donated to the OpenAPI Initiative in 2015. Today "Swagger" mostly names tools around it, such as Swagger UI and Swagger Editor. springdoc generates an OpenAPI document and serves Swagger UI to display it.

2. How does springdoc know that fullName is required and at most 80 characters long?

It reads the Bean Validation annotations on the request record: @NotBlank and @NotNull put the field in required, and @Size(max = 80) becomes maxLength: 80. The same annotations that Spring uses to validate requests also document them, so the two cannot drift apart.

3. Should Swagger UI be enabled in production?

Usually not on a public API. It exposes every endpoint and makes probing easy. Disable springdoc.api-docs.enabled and springdoc.swagger-ui.enabled in the production profile, keep them in development and test, and publish the generated contract file to the people who need it.

4. How do you document JWT security in springdoc?

Declare a security scheme of type HTTP with scheme("bearer") and bearerFormat("JWT") in an OpenAPI bean, and mark protected operations with @SecurityRequirement. Swagger UI then shows an Authorize button and a lock icon, and sends the token in the Authorization header.

Key points

  • springdoc-openapi 3.x is the line for Spring Boot 4; we used 3.2.0, which serves OpenAPI 3.1 at /v3/api-docs and Swagger UI at /swagger-ui.html.
  • Permit only the doc paths (including /v3/api-docs.yaml) in SecurityConfig, and turn the docs off in the prod profile.
  • An OpenAPI bean adds the title, description and the bearer JWT security scheme; @Operation, @ApiResponse and @SecurityRequirement add what code cannot say.
  • Bean Validation annotations become required, maxLength and format in the schema.
  • Commit the generated docs/openapi.yaml so contract changes are reviewed with the code.

Exercise

Document GET /api/auth/me properly. Give it a summary, mark it with the bearer security requirement, and declare a 401 response with no body. Then add @Schema(description = "...", example = "...") to two fields of EmployeeResponse (for example fullName with "Priya Nair" and joinedOn with "2023-04-17"), regenerate docs/openapi.yaml, and say which lines you expect to change in git diff.

Show solution
Java
@Operation(summary = "Who am I? Returns the email and roles from the token")
@SecurityRequirement(name = OpenApiConfig.BEARER)
@ApiResponse(responseCode = "200", description = "The logged-in user")
@ApiResponse(responseCode = "401", description = "No token, or the token is invalid or expired",
        content = @Content)
@GetMapping("/me")
public MeResponse me(@AuthenticationPrincipal Jwt jwt) {
    return new MeResponse(jwt.getSubject(), jwt.getClaimAsStringList("roles"));
}
Java
public record EmployeeResponse(
        Long id,
        @Schema(description = "Name as shown in the directory", example = "Priya Nair") String fullName,
        String email,
        String designation,
        Long departmentId,
        String departmentName,
        @Schema(description = "Joining date, ISO format", example = "2023-04-17") LocalDate joinedOn) {}

After curl -s http://localhost:8080/v3/api-docs.yaml -o docs/openapi.yaml, the diff should add a summary, a security block and a "401" response under /api/auth/me, and add description and example lines under fullName and joinedOn in the EmployeeResponse schema. Nothing else should change; if it does, someone changed the API without saying so.

Quick Quiz

1. Which springdoc-openapi line works with Spring Boot 4?

2. After adding springdoc, /v3/api-docs returned 401. Why?

3. What did @Size(max = 80) on fullName become in the generated schema?

4. How does StaffDesk keep production safe while still sharing the contract?

Learn Spring Boot + React with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call