0
# Core API Generation
1
2
Core SpringDoc functionality that automatically discovers Spring REST endpoints and generates OpenAPI 3 specifications. This system examines Spring Boot applications at runtime to create comprehensive API documentation without manual configuration.
3
4
## Capabilities
5
6
### SpringDocConfiguration
7
8
Main configuration class that sets up the core OpenAPI document generation infrastructure.
9
10
```java { .api }
11
/**
12
* Core configuration class for SpringDoc OpenAPI document generation
13
* Provides essential beans for API discovery and documentation generation
14
*/
15
@Configuration
16
@ConditionalOnProperty(name = "springdoc.api-docs.enabled", matchIfMissing = true)
17
@ConditionalOnBean(OpenAPI.class)
18
public class SpringDocConfiguration {
19
20
/**
21
* Creates OpenAPI resource for serving API documentation
22
* @param openAPI OpenAPI specification builder
23
* @param springDocConfigProperties Configuration properties
24
* @param operationService Service for operation metadata
25
* @param requestMappingInfoHandlerMapping Handler mapping for endpoints
26
* @param actuatorProvider Optional actuator integration
27
* @return OpenApiResource instance for API documentation serving
28
*/
29
@Bean
30
@ConditionalOnMissingBean
31
public OpenApiResource openApiResource(OpenAPI openAPI,
32
SpringDocConfigProperties springDocConfigProperties,
33
OperationService operationService,
34
RequestMappingInfoHandlerMapping requestMappingInfoHandlerMapping,
35
Optional<ActuatorProvider> actuatorProvider);
36
37
/**
38
* Creates operation service for analyzing REST endpoints
39
* @param genericParameterService Service for parameter analysis
40
* @param operationCustomizers List of operation customizers
41
* @param propertyResolverUtils Property resolution utilities
42
* @param springDocConfigProperties Configuration properties
43
* @return OperationService for endpoint analysis
44
*/
45
@Bean
46
@ConditionalOnMissingBean
47
public OperationService operationService(GenericParameterService genericParameterService,
48
List<OperationCustomizer> operationCustomizers, PropertyResolverUtils propertyResolverUtils,
49
SpringDocConfigProperties springDocConfigProperties);
50
51
/**
52
* Creates request builder for analyzing request parameters
53
* @param genericParameterService Parameter analysis service
54
* @param requestBodyService Request body analysis service
55
* @param operationService Operation metadata service
56
* @param parameterCustomizers List of parameter customizers
57
* @param localSpringDocParameterNameDiscoverer Parameter name discovery
58
* @return RequestBuilder for request analysis
59
*/
60
@Bean
61
@ConditionalOnMissingBean
62
public RequestBuilder requestBuilder(GenericParameterService genericParameterService,
63
RequestBodyBuilder requestBodyService, OperationService operationService,
64
List<ParameterCustomizer> parameterCustomizers,
65
LocalSpringDocParameterNameDiscoverer localSpringDocParameterNameDiscoverer);
66
67
/**
68
* Creates response builder for analyzing response types
69
* @param operationService Operation metadata service
70
* @param returnTypeCustomizers List of return type customizers
71
* @param springDocConfigProperties Configuration properties
72
* @param propertyResolverUtils Property resolution utilities
73
* @return ResponseBuilder for response analysis
74
*/
75
@Bean
76
@ConditionalOnMissingBean
77
public ResponseBuilder responseBuilder(OperationService operationService,
78
List<ReturnTypeCustomizer> returnTypeCustomizers, SpringDocConfigProperties springDocConfigProperties,
79
PropertyResolverUtils propertyResolverUtils);
80
}
81
```
82
83
### SpringDocConfigProperties
84
85
Configuration properties that control OpenAPI document generation behavior.
86
87
```java { .api }
88
/**
89
* Configuration properties for SpringDoc OpenAPI generation
90
* Controls API discovery, filtering, and output formatting
91
*/
92
@ConfigurationProperties("springdoc")
93
public class SpringDocConfigProperties {
94
95
/**
96
* Default constructor
97
*/
98
public SpringDocConfigProperties();
99
100
/**
101
* Path where OpenAPI JSON documentation is served
102
* @return API docs path (default: /v3/api-docs)
103
*/
104
public String getApiDocsPath();
105
public void setApiDocsPath(String apiDocsPath);
106
107
/**
108
* Whether OpenAPI documentation generation is enabled
109
* @return true if enabled (default: true)
110
*/
111
public boolean isEnabled();
112
public void setEnabled(boolean enabled);
113
114
/**
115
* Packages to scan for REST controllers
116
* @return comma-separated package names to include
117
*/
118
public String getPackagesToScan();
119
public void setPackagesToScan(String packagesToScan);
120
121
/**
122
* URL patterns to include in documentation
123
* @return comma-separated path patterns to match
124
*/
125
public String getPathsToMatch();
126
public void setPathsToMatch(String pathsToMatch);
127
128
/**
129
* Packages to exclude from scanning
130
* @return comma-separated package names to exclude
131
*/
132
public String getPackagesToExclude();
133
public void setPackagesToExclude(String packagesToExclude);
134
135
/**
136
* URL patterns to exclude from documentation
137
* @return comma-separated path patterns to exclude
138
*/
139
public String getPathsToExclude();
140
public void setPathsToExclude(String pathsToExclude);
141
142
/**
143
* Whether to show Spring Boot Actuator endpoints
144
* @return true to include actuator endpoints
145
*/
146
public boolean isShowActuator();
147
public void setShowActuator(boolean showActuator);
148
149
/**
150
* Whether to use management port for API documentation
151
* @return true to serve docs on management port
152
*/
153
public boolean isUseManagementPort();
154
public void setUseManagementPort(boolean useManagementPort);
155
156
/**
157
* Cache settings for API documentation
158
* @return cache configuration
159
*/
160
public Cache getCache();
161
public void setCache(Cache cache);
162
163
/**
164
* API groups configuration for multi-API documentation
165
* @return list of API group configurations
166
*/
167
public List<GroupConfig> getGroupConfigs();
168
public void setGroupConfigs(List<GroupConfig> groupConfigs);
169
170
/**
171
* Default produces media types for operations without explicit @Produces
172
* @return array of media type strings
173
*/
174
public String[] getDefaultProducesMediaTypes();
175
public void setDefaultProducesMediaTypes(String[] defaultProducesMediaTypes);
176
177
/**
178
* Default consumes media types for operations without explicit @Consumes
179
* @return array of media type strings
180
*/
181
public String[] getDefaultConsumesMediaTypes();
182
public void setDefaultConsumesMediaTypes(String[] defaultConsumesMediaTypes);
183
184
/**
185
* Whether to override existing operation information
186
* @return true to override existing operation data
187
*/
188
public boolean isOverrideWithGenericResponse();
189
public void setOverrideWithGenericResponse(boolean overrideWithGenericResponse);
190
191
/**
192
* Whether to remove broken reference definitions
193
* @return true to clean up broken references
194
*/
195
public boolean isRemoveBrokenReferenceDefinitions();
196
public void setRemoveBrokenReferenceDefinitions(boolean removeBrokenReferenceDefinitions);
197
198
/**
199
* Writer with default pretty printer configuration
200
* @return writer configuration
201
*/
202
public WriterWithDefaultPrettyPrinter getWriterWithDefaultPrettyPrinter();
203
public void setWriterWithDefaultPrettyPrinter(WriterWithDefaultPrettyPrinter writerWithDefaultPrettyPrinter);
204
205
/**
206
* Nested cache configuration class
207
*/
208
public static class Cache {
209
private boolean disabled = false;
210
211
public boolean isDisabled();
212
public void setDisabled(boolean disabled);
213
}
214
215
/**
216
* Nested API group configuration class
217
*/
218
public static class GroupConfig {
219
private String group;
220
private String displayName;
221
private String[] packagesToScan;
222
private String[] pathsToMatch;
223
private String[] packagesToExclude;
224
private String[] pathsToExclude;
225
226
public String getGroup();
227
public void setGroup(String group);
228
229
public String getDisplayName();
230
public void setDisplayName(String displayName);
231
232
public String[] getPackagesToScan();
233
public void setPackagesToScan(String[] packagesToScan);
234
235
public String[] getPathsToMatch();
236
public void setPathsToMatch(String[] pathsToMatch);
237
238
public String[] getPackagesToExclude();
239
public void setPackagesToExclude(String[] packagesToExclude);
240
241
public String[] getPathsToExclude();
242
public void setPathsToExclude(String[] pathsToExclude);
243
}
244
}
245
```
246
247
### OpenApiResource
248
249
REST controller that serves the generated OpenAPI documentation in JSON and YAML formats.
250
251
```java { .api }
252
/**
253
* REST controller serving OpenAPI specification documents
254
* Provides generated API documentation in multiple formats
255
*/
256
@RestController
257
public class OpenApiResource {
258
259
/**
260
* Constructor for OpenAPI resource controller
261
* @param openAPI OpenAPI specification object
262
* @param springDocConfigProperties Configuration properties
263
* @param operationService Service for operation processing
264
* @param requestMappingInfoHandlerMapping Spring MVC handler mapping
265
* @param actuatorProvider Optional actuator integration
266
*/
267
public OpenApiResource(OpenAPI openAPI, SpringDocConfigProperties springDocConfigProperties,
268
OperationService operationService, RequestMappingInfoHandlerMapping requestMappingInfoHandlerMapping,
269
Optional<ActuatorProvider> actuatorProvider);
270
271
/**
272
* Returns OpenAPI specification in JSON format
273
* @param request HTTP request for context
274
* @param locale Locale for internationalization
275
* @return OpenAPI specification as JSON string
276
* @throws JsonProcessingException if JSON serialization fails
277
*/
278
@Operation(hidden = true)
279
@GetMapping(value = "${springdoc.api-docs.path:/v3/api-docs}",
280
produces = MediaType.APPLICATION_JSON_VALUE)
281
public String openapiJson(HttpServletRequest request, Locale locale)
282
throws JsonProcessingException;
283
284
/**
285
* Returns OpenAPI specification in YAML format
286
* @param request HTTP request for context
287
* @param locale Locale for internationalization
288
* @return OpenAPI specification as YAML string
289
* @throws JsonProcessingException if YAML serialization fails
290
*/
291
@Operation(hidden = true)
292
@GetMapping(value = "${springdoc.api-docs.path:/v3/api-docs}.yaml",
293
produces = "application/vnd.oai.openapi")
294
public String openapiYaml(HttpServletRequest request, Locale locale)
295
throws JsonProcessingException;
296
297
/**
298
* Returns OpenAPI specification for specific API group in JSON format
299
* @param group API group name
300
* @param request HTTP request for context
301
* @param locale Locale for internationalization
302
* @return Group-specific OpenAPI specification as JSON
303
* @throws JsonProcessingException if JSON serialization fails
304
*/
305
@Operation(hidden = true)
306
@GetMapping(value = "${springdoc.api-docs.path:/v3/api-docs}/{group}",
307
produces = MediaType.APPLICATION_JSON_VALUE)
308
public String openapiJson(@PathVariable String group, HttpServletRequest request,
309
Locale locale) throws JsonProcessingException;
310
311
/**
312
* Returns OpenAPI specification for specific API group in YAML format
313
* @param group API group name
314
* @param request HTTP request for context
315
* @param locale Locale for internationalization
316
* @return Group-specific OpenAPI specification as YAML
317
* @throws JsonProcessingException if YAML serialization fails
318
*/
319
@Operation(hidden = true)
320
@GetMapping(value = "${springdoc.api-docs.path:/v3/api-docs}/{group}.yaml",
321
produces = "application/vnd.oai.openapi")
322
public String openapiYaml(@PathVariable String group, HttpServletRequest request,
323
Locale locale) throws JsonProcessingException;
324
325
/**
326
* Builds OpenAPI specification for the given request context
327
* @param request HTTP request providing context information
328
* @param locale Locale for localized documentation
329
* @return Complete OpenAPI specification object
330
*/
331
protected OpenAPI getOpenApi(HttpServletRequest request, Locale locale);
332
333
/**
334
* Calculates server URLs for the OpenAPI specification
335
* @param request HTTP request for URL calculation
336
* @param locale Locale context
337
* @return OpenAPI object with calculated server URLs
338
*/
339
protected OpenAPI calculateServerUrl(HttpServletRequest request, Locale locale);
340
}
341
```
342
343
### OperationService
344
345
Service that analyzes Spring MVC operations and generates OpenAPI operation definitions.
346
347
```java { .api }
348
/**
349
* Service for analyzing Spring MVC operations and generating OpenAPI definitions
350
* Core component that processes REST controller methods
351
*/
352
public class OperationService {
353
354
/**
355
* Constructor for operation analysis service
356
* @param genericParameterService Service for parameter type analysis
357
* @param operationCustomizers List of operation customization handlers
358
* @param propertyResolverUtils Utilities for property resolution
359
* @param springDocConfigProperties Configuration properties
360
*/
361
public OperationService(GenericParameterService genericParameterService,
362
List<OperationCustomizer> operationCustomizers, PropertyResolverUtils propertyResolverUtils,
363
SpringDocConfigProperties springDocConfigProperties);
364
365
/**
366
* Builds OpenAPI operation from Spring MVC handler method
367
* @param handlerMethod Spring MVC handler method
368
* @param requestMethod HTTP request method
369
* @param operation Existing operation to enhance
370
* @param methodAttributes Method-level attributes
371
* @param openAPI OpenAPI context object
372
* @return Enhanced Operation object with complete metadata
373
*/
374
public Operation buildOperation(HandlerMethod handlerMethod, RequestMethod requestMethod,
375
Operation operation, MethodAttributes methodAttributes, OpenAPI openAPI);
376
377
/**
378
* Gets operation tags from method annotations
379
* @param handlerMethod Spring MVC handler method
380
* @param operation Operation object to populate
381
* @param locale Locale for localized tags
382
*/
383
public void buildTags(HandlerMethod handlerMethod, Operation operation, Locale locale);
384
385
/**
386
* Processes operation customizers for the given operation
387
* @param operation Operation to customize
388
* @param handlerMethod Spring MVC handler method
389
* @return Customized Operation object
390
*/
391
public Operation customizeOperation(Operation operation, HandlerMethod handlerMethod);
392
393
/**
394
* Determines if operation should be hidden from documentation
395
* @param handlerMethod Spring MVC handler method
396
* @return true if operation should be excluded from documentation
397
*/
398
public boolean isHidden(HandlerMethod handlerMethod);
399
400
/**
401
* Gets operation ID from method or generates unique identifier
402
* @param handlerMethod Spring MVC handler method
403
* @return Unique operation identifier
404
*/
405
public String getOperationId(HandlerMethod handlerMethod);
406
407
/**
408
* Builds operation summary from annotations or method name
409
* @param operation Operation object to populate
410
* @param handlerMethod Spring MVC handler method
411
*/
412
public void buildOperationSummary(Operation operation, HandlerMethod handlerMethod);
413
414
/**
415
* Builds operation description from annotations
416
* @param operation Operation object to populate
417
* @param handlerMethod Spring MVC handler method
418
*/
419
public void buildOperationDescription(Operation operation, HandlerMethod handlerMethod);
420
421
/**
422
* Processes security requirements for the operation
423
* @param operation Operation object to populate
424
* @param handlerMethod Spring MVC handler method
425
*/
426
public void buildSecurityRequirements(Operation operation, HandlerMethod handlerMethod);
427
}
428
```
429
430
## Usage Examples
431
432
### Basic API Documentation Generation
433
434
SpringDoc automatically discovers and documents REST endpoints:
435
436
```java
437
@RestController
438
@RequestMapping("/api/users")
439
public class UserController {
440
441
// This endpoint is automatically documented
442
@GetMapping
443
public List<User> getAllUsers() {
444
return userService.findAll();
445
}
446
447
// SpringDoc generates schema from User class and validation annotations
448
@PostMapping
449
public ResponseEntity<User> createUser(@Valid @RequestBody User user) {
450
User created = userService.save(user);
451
return ResponseEntity.status(201).body(created);
452
}
453
}
454
455
// Model class with validation annotations automatically documented
456
public class User {
457
@NotNull
458
@Size(min = 1, max = 50)
459
private String username;
460
461
462
private String email;
463
464
@Min(18)
465
private Integer age;
466
467
// Getters and setters...
468
}
469
```
470
471
### Enhanced Documentation with Annotations
472
473
Add OpenAPI annotations for comprehensive documentation:
474
475
```java
476
@RestController
477
@RequestMapping("/api/products")
478
@Tag(name = "Product Management", description = "Operations for managing products")
479
public class ProductController {
480
481
@GetMapping("/{id}")
482
@Operation(
483
summary = "Get product by ID",
484
description = "Retrieves a single product by its unique identifier",
485
responses = {
486
@ApiResponse(responseCode = "200", description = "Product found",
487
content = @Content(schema = @Schema(implementation = Product.class))),
488
@ApiResponse(responseCode = "404", description = "Product not found")
489
}
490
)
491
public ResponseEntity<Product> getProduct(
492
@Parameter(description = "Product ID", example = "12345")
493
@PathVariable Long id) {
494
return productService.findById(id)
495
.map(ResponseEntity::ok)
496
.orElse(ResponseEntity.notFound().build());
497
}
498
499
@PostMapping
500
@Operation(summary = "Create new product")
501
@SecurityRequirement(name = "bearerAuth")
502
public ResponseEntity<Product> createProduct(
503
@Parameter(description = "Product to create")
504
@Valid @RequestBody CreateProductRequest request) {
505
Product created = productService.create(request);
506
return ResponseEntity.status(201).body(created);
507
}
508
}
509
```
510
511
### Configuration-Based API Filtering
512
513
Control which APIs are documented through configuration:
514
515
```yaml
516
springdoc:
517
api-docs:
518
enabled: true
519
path: /v3/api-docs
520
packages-to-scan: com.example.api
521
paths-to-match: /api/**
522
paths-to-exclude: /api/internal/**
523
show-actuator: false
524
```
525
526
```java
527
// Only controllers in com.example.api package matching /api/**
528
// (excluding /api/internal/**) will be documented
529
@RestController
530
@RequestMapping("/api/public") // Will be documented
531
public class PublicApiController {
532
// ...
533
}
534
535
@RestController
536
@RequestMapping("/api/internal") // Will be excluded
537
public class InternalApiController {
538
// ...
539
}
540
541
@RestController
542
@RequestMapping("/admin") // Will be excluded (doesn't match /api/**)
543
public class AdminController {
544
// ...
545
}
546
```
547
548
### Multiple API Groups
549
550
Configure multiple API groups for microservice documentation:
551
552
```yaml
553
springdoc:
554
group-configs:
555
- group: public-api
556
display-name: "Public API"
557
paths-to-match: /api/public/**
558
- group: admin-api
559
display-name: "Admin API"
560
paths-to-match: /api/admin/**
561
packages-to-scan: com.example.admin
562
```
563
564
```java
565
// Access group-specific documentation:
566
// GET /v3/api-docs/public-api - Public API documentation
567
// GET /v3/api-docs/admin-api - Admin API documentation
568
// GET /v3/api-docs - Complete API documentation
569
```
570
571
### Custom OpenAPI Configuration
572
573
Customize the generated OpenAPI specification:
574
575
```java
576
@Configuration
577
public class OpenApiConfig {
578
579
@Bean
580
public OpenAPI customOpenAPI() {
581
return new OpenAPI()
582
.info(new Info()
583
.title("My API")
584
.version("1.0")
585
.description("Comprehensive API for my application")
586
.contact(new Contact()
587
.name("API Support")
588
.email("support@example.com")
589
.url("https://example.com/support"))
590
.license(new License()
591
.name("MIT")
592
.url("https://opensource.org/licenses/MIT")))
593
.servers(List.of(
594
new Server().url("https://api.example.com").description("Production"),
595
new Server().url("https://staging-api.example.com").description("Staging")
596
))
597
.addSecurityItem(new SecurityRequirement().addList("bearerAuth"))
598
.components(new Components()
599
.addSecuritySchemes("bearerAuth", new SecurityScheme()
600
.type(SecurityScheme.Type.HTTP)
601
.scheme("bearer")
602
.bearerFormat("JWT")));
603
}
604
605
@Bean
606
public OperationCustomizer operationIdCustomizer() {
607
return (operation, handlerMethod) -> {
608
String className = handlerMethod.getBeanType().getSimpleName();
609
String methodName = handlerMethod.getMethod().getName();
610
operation.setOperationId(className + "_" + methodName);
611
return operation;
612
};
613
}
614
}
615
```
616
617
## Performance Considerations
618
619
### Lazy Loading
620
621
SpringDoc supports lazy loading for better startup performance:
622
623
```yaml
624
springdoc:
625
api-docs:
626
enabled: true
627
lazy-initialization: true
628
cache:
629
disabled: false # Enable caching for production
630
```
631
632
### Production Optimizations
633
634
```yaml
635
# Production configuration
636
springdoc:
637
api-docs:
638
enabled: true # Keep docs enabled
639
swagger-ui:
640
enabled: false # Disable UI in production
641
cache:
642
disabled: false # Enable caching
643
writer-with-default-pretty-printer: false # Compact JSON output
644
```
645
646
### Large API Handling
647
648
For applications with many endpoints:
649
650
```yaml
651
springdoc:
652
packages-to-scan: com.example.api # Limit scanning scope
653
paths-to-match: /api/** # Filter by path patterns
654
remove-broken-reference-definitions: true # Clean up unused schemas
655
override-with-generic-response: false # Avoid generic response pollution
656
```