Adding springdoc-openapi
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's frontend team wants live docs without anyone writing a spec by hand. When a controller changes, the docs must change with it, and they must not stay open to everyone once the shop goes live.
The springdoc-openapi-starter-webmvc-ui dependency
springdoc-openapi is a library that reads your Spring MVC controllers while the app runs and serves their OpenAPI document and a Swagger UI page. One starter dependency, springdoc-openapi-starter-webmvc-ui, adds all of it.
Add the springdoc starter to pom.xml, with its version kept in a property.
Example 1 · pom.xml: the springdoc starter for Boot 4
Runs in: the shoplite-api Spring Boot project
<!-- pom.xml (parts that change) --><properties> <java.version>17</java.version> <!-- springdoc is not managed by Spring Boot: pin a version made for Boot 4 --> <springdoc.version>3.1.1</springdoc.version></properties><dependencies> <!-- spring-boot-starter-webmvc, -validation and -actuator stay as they are --> <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> <version>${springdoc.version}</version> </dependency></dependencies>$ mvn dependency:tree -Dincludes=org.springdoc,io.swagger.core.v3,org.webjars [INFO] --- dependency:3.10.0:tree (default-cli) @ shoplite-api --- [INFO] com.shoplite:shoplite-api:jar:0.0.1-SNAPSHOT [INFO] \- org.springdoc:springdoc-openapi-starter-webmvc-ui:jar:3.1.1:compile [INFO] +- org.springdoc:springdoc-openapi-starter-webmvc-api:jar:3.1.1:compile [INFO] | \- org.springdoc:springdoc-openapi-starter-common:jar:3.1.1:compile [INFO] | \- io.swagger.core.v3:swagger-core-jakarta:jar:2.2.55:compile [INFO] | +- io.swagger.core.v3:swagger-annotations-jakarta:jar:2.2.55:compile [INFO] | \- io.swagger.core.v3:swagger-models-jakarta:jar:2.2.55:compile [INFO] +- org.webjars:swagger-ui:jar:5.32.14:compile [INFO] \- org.webjars:webjars-locator-lite:jar:1.1.4:compile [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS
What this code does
- One dependency brings three parts: the springdoc generator (
-webmvc-apiand-common), the Swagger models and annotations (swagger-core-jakarta2.2.55), and Swagger UI itself (org.webjars:swagger-ui5.32.14). - The version comes from the
springdoc.versionproperty. Spring Boot's parent manages Spring, Jackson and Tomcat, but not springdoc. -Dincludesfilters the tree to these groups, so the output stays short. Your Maven timings will differ.
The starter brings the spec generator, the Swagger annotations (io.swagger.v3.oas.annotations) and the Swagger UI web files. Spring Boot does not manage springdoc's version, so you write it, and it must match your Boot line: springdoc 1.x is for Boot 2, 2.x for Boot 3, and 3.x for Boot 4. An older line may still start (2.8.13 did, for ShopLite), but nobody tests that pair, so a later change can break it without warning.
This module uses springdoc 3.1.1, built against Spring Boot 4.1.0 and checked here with Boot 4.1.1. A <properties> entry means one line changes when you upgrade. springdoc-openapi-starter-webmvc-api is the same generator without Swagger UI, for apps that only publish the JSON.
/v3/api-docs and /swagger-ui.html
/v3/api-docs is the URL where springdoc serves the generated OpenAPI document as JSON; /v3/api-docs.yaml gives YAML. /swagger-ui.html redirects to the Swagger UI page, which loads that document and draws it.
Start ShopLite and call the two URLs springdoc adds. No settings are changed yet.
Example 2 · The two URLs springdoc adds, with no settings yet
Runs in: the shoplite-api Spring Boot project
mvn spring-boot:run# in a second terminalcurl -i http://localhost:8080/swagger-ui.htmlcurl http://localhost:8080/v3/api-docs$ mvn spring-boot:run
2026-10-16T10:38:30.001+05:30 INFO 15760 --- [shoplite-api] [ main] com.shoplite.ShopliteApiApplication : Started ShopliteApiApplication in 18.672 seconds (process running for 20.231)
2026-10-16T10:38:30.865+05:30 WARN 15760 --- [shoplite-api] [ main] o.s.core.events.SpringDocAppInitializer : SpringDoc /v3/api-docs endpoint is enabled by default. To disable it in production, set the property 'springdoc.api-docs.enabled=false'
2026-10-16T10:38:30.867+05:30 WARN 15760 --- [shoplite-api] [ main] o.s.core.events.SpringDocAppInitializer : SpringDoc /swagger-ui.html endpoint is enabled by default. To disable it in production, set the property 'springdoc.swagger-ui.enabled=false'
...
2026-10-16T10:38:35.027+05:30 INFO 15760 --- [shoplite-api] [io-8080-exec-1] o.springdoc.api.AbstractOpenApiResource : Init duration for springdoc-openapi is: 2033 ms
$ curl -i http://localhost:8080/swagger-ui.html
HTTP/1.1 302
Location: /swagger-ui/index.html
Content-Length: 0
Date: Fri, 16 Oct 2026 05:08:37 GMT
$ curl http://localhost:8080/v3/api-docs (formatted and trimmed)
{
"openapi": "3.1.0",
"info": {
"title": "OpenAPI definition",
"version": "v0"
},
"servers": [
{
"url": "http://localhost:8080",
"description": "Generated server url"
}
],
"paths": {
"/api/v1/products/{id}": {
"get": {
"tags": [
"product-controller"
],
"operationId": "get",
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"schema": {
"type": "integer",
"format": "int64"
}
}
],
"responses": {
"200": {
"description": "OK",
"content": {
"*/*": {
"schema": {
"$ref": "#/components/schemas/ProductResponse"
}
}
}
}
}
},
...
},
...
"/api": {
"get": {
"tags": [
"api-info-controller"
],
"operationId": "info",
"responses": {
"200": {
"description": "OK",
"content": {
"*/*": {
"schema": {
"$ref": "#/components/schemas/ApiInfo"
}
}
}
}
}
}
}
},
"components": {
"schemas": {
"ApiInfo": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"version": {
"type": "string"
}
}
},
...
}
}
}What this code does
- The startup log has the two springdoc warnings; the "Init duration" line appears on the first
/v3/api-docsrequest, when the document is built. /swagger-ui.htmlanswers 302 withLocation: /swagger-ui/index.html; a browser follows it and shows the page. Swagger UI then fetches/v3/api-docs.- The default document has a placeholder title and
v0, class-name tags,*/*response types and the/apiinfo endpoint, which is not part of the v1 contract.
With no settings, the document has every controller, including the /api info endpoint from the first ShopLite project. The title is "OpenAPI definition", the version "v0", each tag is a class name such as product-controller, and the response type is */* ("anything"), because the methods do not say what they produce.
springdoc builds the document on the first request (about 2 seconds here) and caches it. At startup it logs two warnings: the docs are on by default, and production should turn them off. Open http://localhost:8080/swagger-ui.html in a browser to see the page.
Order of execution
From dependency to docs page
Put the steps in the order they happen.
An OpenAPI bean with title, version, description and contact
An OpenAPI bean (class io.swagger.v3.oas.models.OpenAPI) is the starting document that springdoc fills in. What you set on it, such as info, stays; springdoc adds the paths and schemas from the controllers.
This configuration class gives ShopLite's API a title, version, description and contact.
Example 3 · src/main/java/com/shoplite/common/OpenApiConfig.java
Runs in: the shoplite-api Spring Boot project
// src/main/java/com/shoplite/common/OpenApiConfig.javapackage com.shoplite.common;
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;
import io.swagger.v3.oas.models.OpenAPI;import io.swagger.v3.oas.models.info.Contact;import io.swagger.v3.oas.models.info.Info;
/** The cover page of ShopLite's API docs: title, version, description and contact. */@Configurationclass OpenApiConfig {
@Bean OpenAPI shopLiteOpenApi() { return new OpenAPI() .info(new Info() .title("ShopLite API") .version("v1") .description("REST API of ShopLite, a small online store for India. " + "Money is in rupees with two decimals; errors use Problem Details (RFC 9457).") .contact(new Contact() .name("ShopLite API team") .email("api@shoplite.example") .url("https://shoplite.example"))); }}$ curl http://localhost:8080/v3/api-docs (formatted and trimmed)
{
"openapi": "3.1.0",
"info": {
"title": "ShopLite API",
"description": "REST API of ShopLite, a small online store for India. Money is in rupees with two decimals; errors use Problem Details (RFC 9457).",
"contact": {
"name": "ShopLite API team",
"url": "https://shoplite.example",
"email": "api@shoplite.example"
},
"version": "v1"
},
"servers": [
{
"url": "http://localhost:8080",
"description": "Generated server url"
}
],
...
}What this code does
- The
OpenAPIbean'sinforeplaces "OpenAPI definition" andv0.InfoandContactare plain model classes with chained setters. - Swagger UI shows the title with a
v1badge and anOAS 3.1badge, the description below it, and "ShopLite API team - Website" and "Send email to ShopLite API team" links. serversis still filled by springdoc from the request ("Generated server url"), so it is always the address you called.
info is the cover page: title, version (the API's version, v1, not the jar's), description (the rules every endpoint shares, such as money and errors) and contact (who to ask). Swagger UI shows them at the top, with the version as a badge and the contact as "Website" and "Send email" links.
ShopLite puts this class in com.shoplite.common, next to the global error handler, because it belongs to the whole API and not to one feature.
Limiting docs to /api/** and grouping by feature
GroupedOpenApi is a bean that creates a separate OpenAPI document for part of the API, served at /v3/api-docs/{group}. Swagger UI then shows a "Select a definition" box to switch between groups.
Two properties come first: only /api/v1 goes into the docs, and responses are typed as JSON. A GroupedOpenApi bean per feature follows.
Example 4 · application.properties: only /api/v1, and JSON instead of /
Runs in: the shoplite-api Spring Boot project
# src/main/resources/application.properties (the lines added in this lesson)# API docs (springdoc-openapi)springdoc.paths-to-match=/api/v1/**springdoc.default-produces-media-type=application/json$ curl http://localhost:8080/v3/api-docs (formatted and trimmed)
{
"paths": {
"/api/v1/products/{id}": {
"get": {
"tags": [
"product-controller"
],
"operationId": "get",
...
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProductResponse"
}
}
}
}
}
},
...
},
"/api/v1/categories/{id}": { ... },
"/api/v1/products": { ... },
"/api/v1/categories": { ... }
}
}
Paths in the document: /api/v1/products/{id}, /api/v1/categories/{id}, /api/v1/products, /api/v1/categories
(/api is gone, and no response says */* any more)What this code does
springdoc.paths-to-match=/api/v1/**keeps only the contract's paths; the/apiinfo endpoint still works, it is just not documented.default-produces-media-typemakes every success responseapplication/json. Error responses get their ownapplication/problem+jsontype in the next lesson.- The tags and operation ids are still guesses (
product-controller,get). Annotations fix those next.
Example 5 · ApiGroupsConfig.java: one docs group per feature
Runs in: a copy of the shoplite-api project
// src/main/java/com/shoplite/common/ApiGroupsConfig.javapackage com.shoplite.common;
import org.springdoc.core.models.GroupedOpenApi;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;
/** One docs group per feature: each group is its own spec and its own entry in Swagger UI. */@Configurationclass ApiGroupsConfig {
@Bean GroupedOpenApi categoriesApi() { return GroupedOpenApi.builder() .group("categories") .pathsToMatch("/api/v1/categories/**") .build(); }
@Bean GroupedOpenApi productsApi() { return GroupedOpenApi.builder() .group("products") .pathsToMatch("/api/v1/products/**") .build(); }}$ curl http://localhost:8080/v3/api-docs/swagger-config (formatted)
{
"configUrl": "/v3/api-docs/swagger-config",
"oauth2RedirectUrl": "http://localhost:8080/swagger-ui/oauth2-redirect.html",
"urls": [
{
"url": "/v3/api-docs/categories",
"name": "categories"
},
{
"url": "/v3/api-docs/products",
"name": "products"
}
],
"validatorUrl": ""
}
$ curl http://localhost:8080/v3/api-docs/categories (paths only)
{
"paths": {
"/api/v1/categories/{id}": { ... },
"/api/v1/categories": { ... }
}
}
$ curl http://localhost:8080/v3/api-docs/products (paths only)
{
"paths": {
"/api/v1/products/{id}": { ... },
"/api/v1/products": { ... }
}
}What this code does
- Each
GroupedOpenApibean is a separate document.swagger-configlists them, and Swagger UI shows them in its "Select a definition" box. - Each group has only its feature's paths. This run had no
springdoc.paths-to-matchline; with that line present, both groups listed all four paths. - ShopLite does not keep this file yet: with two features, one document is simpler for readers and for Postman. Keep it in mind for when customers and orders arrive.
springdoc.paths-to-match lists the URL patterns that go into the document: /api/v1/** keeps the four /api/v1 paths and drops /api. springdoc.default-produces-media-type=application/json replaces the */* guess with the type ShopLite really sends. Groups help a large API: one per feature, or "public" and "admin".
Use one approach or the other. With springdoc 3.1.1, the global springdoc.paths-to-match also applied to every group and replaced the group's own paths, so both groups showed all four paths. ShopLite has two features so far, so it keeps one document with paths-to-match; groups are worth it once customers and orders arrive.
/** also matches the path itself: /api/v1/categories/** covers /api/v1/categories and /api/v1/categories/7.Turning Swagger UI off in the prod profile
Turning the docs off in production means setting springdoc.api-docs.enabled=false and springdoc.swagger-ui.enabled=false in application-prod.properties, so only the prod profile loses them and dev keeps them.
These two properties go in application-prod.properties. Run ShopLite with the dev profile and then the prod profile to compare.
Example 6 · application-prod.properties: no docs in production
Runs in: the shoplite-api Spring Boot project
# src/main/resources/application-prod.propertieslogging.level.com.shoplite=INFOmanagement.endpoint.health.show-details=never# No API docs or Swagger UI in productionspringdoc.api-docs.enabled=falsespringdoc.swagger-ui.enabled=false$ java -jar target/shoplite-api-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod
... The following 1 profile is active: "prod"
... Started ShopliteApiApplication in 14.651 seconds (process running for 16.091)
(no SpringDoc warnings this time)
$ curl -i http://localhost:8080/v3/api-docs
HTTP/1.1 404
Content-Type: application/problem+json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:27:51 GMT
{"title":"Not Found","status":404,"detail":"No static resource v3/api-docs.","instance":"/v3/api-docs"}
$ curl -i http://localhost:8080/swagger-ui.html
HTTP/1.1 404
Content-Disposition: inline;filename=f.txt
Content-Type: application/problem+json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:27:51 GMT
{"title":"Not Found","status":404,"detail":"No static resource swagger-ui.html.","instance":"/swagger-ui.html"}
$ curl http://localhost:8080/api/v1/products/1
{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","categoryId":2,"categoryName":"Mobiles","price":17999.00,"stock":40,"isActive":true}What this code does
- With the
prodprofile both URLs answer 404, while the API itself works as before. - The two startup warnings are gone, because the docs are now switched off on purpose.
- Run
mvn spring-boot:runwithout a profile (ShopLite's default isdev) and the docs come back. One code base, different behaviour per environment.
The spec is a full map of your API for anyone who finds it, and Try it out is a ready-made client that sends real POST and DELETE requests to real data. A public API that wants public docs publishes a reviewed copy of the spec instead, or puts the docs behind login (Section 17).
Turn off both. If only Swagger UI is off, /v3/api-docs still hands out the whole map; if only the JSON is off, Swagger UI loads an empty page with an error.
Fix the error
Switch both off
Each prod file leaves one door open. Pick the line that closes it.
Round 1 of 2
Swagger UI still opens in prod. Fix line 2.
Error
GET /swagger-ui.html -> 302 Swagger UI loads, but the page says: Failed to load API definition
Next step
Check your understanding
11 quick questions