Sub topic 6
Describing the API with an OpenAPI bean
An OpenAPI document starts with a header block: a title, a version, a description, contact details and the servers that host the API. springdoc fills this header with placeholder values until you supply your own. This chapter shows how to supply them with an OpenAPI bean.
This chapter assumes you have springdoc-openapi running in a Spring Boot 3 project, as set up earlier in this tutorial. You should also be comfortable with @Configuration classes and @Bean methods. You should be able to open /v3/api-docs and Swagger UI.
What the default document looks like
With no configuration, the top of the generated JSON looks like this:
{
"openapi": "3.0.1",
"info": {
"title": "OpenAPI definition",
"version": "v0"
},
"servers": [
{ "url": "http://localhost:8080", "description": "Generated server url" }
],
"paths": {}
}The title "OpenAPI definition" and version "v0" appear at the top of Swagger UI. They tell a reader nothing about your service. The servers entry is built from the URL of the incoming request, so it changes depending on how you reach the application.
How the bean fits into generation
springdoc builds the document in two stages. First it scans your controllers and models and produces paths and components. Then it looks for an OpenAPI bean in the Spring context and uses it as the base, so the metadata you define is carried into the final result.
You write the bean only for the parts of the document that code scanning cannot know: who owns the API, which license applies, where it is deployed.
A complete metadata bean
The bean below sets the main header fields. The classes come from io.swagger.v3.oas.models, which the springdoc starter brings in transitively.
import io.swagger.v3.oas.models.ExternalDocumentation;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.servers.Server;
import io.swagger.v3.oas.models.tags.Tag;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OpenApiConfig {
@Bean
public OpenAPI libraryOpenApi() {
return new OpenAPI()
.info(new Info()
.title("Library API")
.version("1.0.0")
.description("Manage the book catalog.")
.termsOfService("https://example.com/terms")
.contact(new Contact()
.name("Library Platform Team")
.email("[email protected]")
.url("https://example.com/team"))
.license(new License()
.name("Apache 2.0")
.url("https://www.apache.org/licenses/LICENSE-2.0")))
.servers(List.of(
new Server().url("https://api.example.com").description("Production"),
new Server().url("https://staging.example.com").description("Staging")))
.externalDocs(new ExternalDocumentation()
.description("Developer guide")
.url("https://example.com/docs"))
.addTagsItem(new Tag()
.name("Books")
.description("Operations on the book catalog"));
}
}Each part does a specific job:
| Field | Purpose | Where you see it |
|---|---|---|
| `info.title`, `info.version` | Names the API and its release | Heading in Swagger UI |
| `info.description` | Overview text, Markdown allowed | Under the title |
| `contact`, `license` | Ownership and legal terms | Links under the description |
| `servers` | Base URLs for "Try it out" | Server drop-down in Swagger UI |
| `externalDocs` | Link to longer documentation | Link near the top |
| `tags` | Descriptions for the tags used on controllers | Group headers in Swagger UI |
Run the application and fetch the document to confirm the change:
curl -s http://localhost:8080/v3/api-docs | head -c 600The info block should now show "Library API" and "1.0.0".
Servers and "Try it out"
Swagger UI sends test requests to the server selected in its drop-down. If you list only production URLs, a learner who clicks "Execute" sends a real request to production. Two habits reduce that risk:
- List local or staging servers first, because the first entry is the default selection.
- Leave
serversunset in development. springdoc then derives the URL from the request, which works on localhost with no editing.
Behind a reverse proxy, the derived URL can be wrong, for example http:// instead of https://, or an internal host name. In that case, set Spring Boot's server.forward-headers-strategy=framework so the application honors X-Forwarded-* headers. An explicit servers list also fixes the problem.
The annotation alternative
You can set the same info data without a bean, using @OpenAPIDefinition on any configuration class. The security chapter later in this tutorial uses this style:
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.info.Contact;
import io.swagger.v3.oas.annotations.info.Info;
import org.springframework.context.annotation.Configuration;
@Configuration
@OpenAPIDefinition(info = @Info(
title = "Library API",
version = "1.0.0",
description = "Manage the book catalog.",
contact = @Contact(name = "Library Platform Team", email = "[email protected]")))
public class OpenApiAnnotationConfig {
}Both approaches produce the same header. The choice is mostly about what else you need:
| Need | Bean | Annotation |
|---|---|---|
| Static metadata only | Works | Works, and is shorter |
| Values computed at startup, such as the version from build info | Works | Limited to constants |
| Injecting `@Value` properties or other beans | Works | Not possible |
| Everything in one typed object | Works | Spread across annotations |
Pick one style for the whole application. Defining the header in both places leads to confusing results, because you then have to work out which values win. If the output looks wrong, check /v3/api-docs and remove the duplicate.
Computing values from properties
A bean method can read configuration, so the version in the documentation does not drift from the application's version:
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class VersionedOpenApiConfig {
@Bean
public OpenAPI versionedOpenApi(@Value("${app.version:1.0.0}") String appVersion) {
return new OpenAPI().info(new Info()
.title("Library API")
.version(appVersion));
}
}If you use this class instead of OpenApiConfig, remove the other one. Having two beans is one of the errors covered next.
Customizing the finished document
Sometimes you need to change the document after scanning, for example to add a header to every operation or to edit generated tags. springdoc offers OpenApiCustomizer for that. It receives the assembled OpenAPI object just before it is served:
import io.swagger.v3.oas.models.tags.Tag;
import org.springdoc.core.customizers.OpenApiCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OpenApiCustomizerConfig {
@Bean
public OpenApiCustomizer addBooksTagDescription() {
return openApi -> openApi.addTagsItem(
new Tag().name("Books").description("Operations on the book catalog"));
}
}Use the bean for the base metadata and a customizer for adjustments that depend on the scanned result. A customizer bean can coexist with the OpenAPI bean.
Common errors
- The title is still "OpenAPI definition". The configuration class is outside the package scan of your
@SpringBootApplicationclass, or it lacks@Configuration. Move it under the main package and check that the bean is created. - Two
OpenAPIbeans. Spring cannot decide which one springdoc should use, and you may see aNoUniqueBeanDefinitionExceptionor an unexpected header. Keep exactly one. - Tag descriptions do not appear. The tag name in the bean must match the controller's
@Tag(name = ...)exactly, including case. A mismatch creates two separate groups. - Wrong server URL in "Try it out". See the proxy notes above. Requests fail with CORS or mixed-content errors when the page is served over HTTPS but the server URL is HTTP.
- Changes do not show. Swagger UI may be using a cached copy. Reload the page with the cache bypassed, or fetch
/v3/api-docswithcurlto see the real output.
Exercise
Your Swagger UI still shows the title "OpenAPI definition" and version "v0" even though you wrote an OpenAPI bean with title "Orders API". Name two likely causes and one way to check each.
Show answer
First, the configuration class may not be picked up: it lacks @Configuration or sits outside the package scanned by the @SpringBootApplication class. Check by confirming the bean exists, for example with a log statement in the @Bean method or by injecting OpenAPI in a test. Second, a second OpenAPI bean or an @OpenAPIDefinition annotation may be overriding or conflicting with it. Check by searching the project for other OpenAPI beans and annotations, then fetch /v3/api-docs with curl and read the info block directly.
Exercise
You want the documented version to follow the application's version property app.version, with a default of 1.0.0. Should you use an @OpenAPIDefinition annotation or an OpenAPI bean, and why?
Show answer
Use an OpenAPI bean. Annotation attributes must be compile-time constants, so they cannot read a property. A @Bean method can take @Value("${app.version:1.0.0}") as a parameter and pass it to Info.version.