Openapi To Application Java Spring Boot
GitHubOfficialFirst committed by jduboisDistributed by GitHub
- Skill
- Tool integration
- Software development
- MIT
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a structured approach to building Spring Boot applications using the spec-first methodology. By utilizing the openapi-generator plugin within Maven or Gradle, developers can automatically generate API interfaces and Data Transfer Objects (DTOs) directly from an OpenAPI 3 specification. The process emphasizes maintaining the OpenAPI file as the single source of truth, ensuring that generated code remains untouched while developers focus on implementing business logic, persistence, security, and testing.
What it does
- Configures Maven or Gradle to generate Java interfaces and DTOs from OpenAPI 3.0/3.1 files.
- Ensures generated code is treated as read-only, with logic implemented in separate service layers.
- Provides configuration options for Spring Boot 3.x and 4.x compatibility.
- Guides the implementation of controllers, persistence layers, and security configurations.
- Outlines testing strategies for validating API operations against the specification.
- Advises on handling validation constraints and error responses according to the spec.
When to use it
- When starting a new Spring Boot API project where an OpenAPI specification already exists.
- When you need to ensure your API implementation strictly adheres to a defined contract.
- When you want to automate the creation of boilerplate DTOs and API interfaces.
- When working in a team environment where the API contract is shared and version-controlled.
Advantages
- Maintains a single source of truth via the OpenAPI specification.
- Reduces manual boilerplate code for DTOs and API interfaces.
- Ensures consistent API structure and validation across the application.
- Supports modern Spring Boot features and build tool configurations.
- Promotes clean architecture by separating generated contracts from business logic.
Usage examples
- “Set up a new Spring Boot project using this petstore.yaml file as the API contract.”
- The agent will create the project structure, configure the openapi-generator plugin in the build file, and generate the necessary API interfaces and models.
- “How do I configure the OpenAPI generator for a Gradle project using Kotlin DSL?”
- The agent provides the specific openApiGenerate block configuration, including necessary dependencies and task dependencies for the compileJava task.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/github/openapi-to-application-java-spring-boot/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip openapi-to-application-java-spring-boot.zip -d .agents/skills
Documentation by jdubois
Spring Boot application from an OpenAPI spec
Spec-first: the OpenAPI file is the source of truth. Generate interfaces and DTOs only at build time (never commit generated code), then hand-write the implementation. Verified with Spring Boot 4.0.8 and 4.1.1, openapi-generator 7.26.0 (Maven plugin, Gradle Groovy and Kotlin DSL), JDK 21+.
Step 0: Detect and gather
Existing
pom.xml/build.gradle(.kts): keep its build tool and Spring Boot version, never upgrade implicitly, add the generator to it. Otherwise create the project with thecreate-spring-boot-java-projectskill (dependencies:web,validation,actuator; adddata-jpa,postgresql,securityonly if needed).Get the spec (file, URL or pasted) and save it as
src/main/resources/openapi/<name>.yaml. Accept 3.0.x and 3.1.x; Swagger 2.0 must be converted first.Ask only what the spec does not answer: persistence (in-memory vs database), authentication, package name.
Step 1: Review the spec
Check unique operationIds (they become method names), tags (they become one interface each), reusable components/schemas, required lists, validation constraints (minLength, maximum, pattern), error responses and securitySchemes. Flag gaps and fix the spec rather than the generated code.
Step 2: Configure the generator
Pin the version in a property; check the latest on Maven Central or the generator docs before changing it.
Maven (pom.xml, in <build><plugins>, before spring-boot-maven-plugin):
<plugin>
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<version>${openapi-generator.version}</version> <!-- 7.26.0 -->
<executions>
<execution>
<goals><goal>generate</goal></goals>
<configuration>
<inputSpec>${project.basedir}/src/main/resources/openapi/petstore.yaml</inputSpec>
<generatorName>spring</generatorName>
<apiPackage>com.example.petstore.api</apiPackage>
<modelPackage>com.example.petstore.api.model</modelPackage>
<generateSupportingFiles>false</generateSupportingFiles>
<configOptions>
<interfaceOnly>true</interfaceOnly>
<requestMappingMode>api_interface</requestMappingMode>
<useSpringBoot4>true</useSpringBoot4>
<useJackson3>true</useJackson3>
<useSpringBuiltInValidation>true</useSpringBuiltInValidation>
<useTags>true</useTags>
<skipDefaultInterface>true</skipDefaultInterface>
<openApiNullable>false</openApiNullable>
<documentationProvider>none</documentationProvider>
<annotationLibrary>none</annotationLibrary>
</configOptions>
</configuration>
</execution>
</executions>
</plugin>Gradle (Groovy DSL; plugin id 'org.openapi.generator' version '7.26.0'):
openApiGenerate {
generatorName = 'spring'
inputSpec = "$projectDir/src/main/resources/openapi/petstore.yaml".toString()
outputDir = layout.buildDirectory.dir('generated/openapi').get().asFile.path
apiPackage = 'com.example.petstore.api'
modelPackage = 'com.example.petstore.api.model'
generateApiTests = false
generateModelTests = false
generateSupportingFiles = false
configOptions = [interfaceOnly: 'true', requestMappingMode: 'api_interface', useSpringBoot4: 'true', useJackson3: 'true', useSpringBuiltInValidation: 'true', useTags: 'true',
skipDefaultInterface: 'true', openApiNullable: 'false', documentationProvider: 'none', annotationLibrary: 'none']
}
sourceSets.main.java.srcDir layout.buildDirectory.dir('generated/openapi/src/main/java')
tasks.named('compileJava') { dependsOn 'openApiGenerate' }Gradle (Kotlin DSL; plugin id("org.openapi.generator") version "7.26.0", resolved from the Gradle plugin portal, so keep gradlePluginPortal() in pluginManagement):
openApiGenerate {
generatorName.set("spring")
inputSpec.set("$projectDir/src/main/resources/openapi/petstore.yaml")
outputDir.set(layout.buildDirectory.dir("generated/openapi").get().asFile.path)
apiPackage.set("com.example.petstore.api")
modelPackage.set("com.example.petstore.api.model")
generateApiTests.set(false)
generateModelTests.set(false)
generateSupportingFiles.set(false)
configOptions.set(mapOf("interfaceOnly" to "true", "requestMappingMode" to "api_interface", "useSpringBoot4" to "true", "useJackson3" to "true", "useSpringBuiltInValidation" to "true", "useTags" to "true",
"skipDefaultInterface" to "true", "openApiNullable" to "false", "documentationProvider" to "none", "annotationLibrary" to "none"))
}
sourceSets.main { java.srcDir(layout.buildDirectory.dir("generated/openapi/src/main/java")) }
tasks.compileJava { dependsOn("openApiGenerate") }Option notes:
Spring Boot 3.x: drop
useSpringBoot4anduseJackson3(useSpringBoot3=trueis the default). Boot 4 needs both options; Jackson 3 is only allowed withuseSpringBoot4.Request-parameter validation: for Boot 3.2+/4 (Framework 6.1+), keep
useSpringBuiltInValidation=truein all build-tool configurations. It omits type-level@Validatedfrom generated API interfaces so MVC handles constrained query/path parameters throughHandlerMethodValidationException. For Boot 3.0/3.1, leave this optionfalseto retain AOP validation and explicitly map request-parameterConstraintViolationExceptionto HTTP 400 with the spec's error body. Do not blanket-map service-layer constraint violations to 400. Never patch generated interfaces to change validation behavior.Base paths:
requestMappingMode=api_interfaceputs the class-level base-path mapping on the interface when no controller is generated. Forservers: [{url: /v1}]and path/pets, verify/v1/pets; do not add the same/v1prefix again through controller mappings,server.servlet.context-pathor proxy rewriting.interfaceOnly=truegenerates<Tag>Apiinterfaces (with@RequestMapping/validation annotations) and models.delegatePattern=true(instead) generates controllers calling a<Tag>ApiDelegateyou implement; preferinterfaceOnly, it is simpler. If you usedelegatePattern(verified on Boot 4.1.1): dropskipDefaultInterface(it breaks the generated delegate, compile errors); generate onlyApiUtil.javaas supporting file, otherwise the default delegate methods fail withcannot find symbol ApiUtiland a full set of supporting files adds anOpenApiGeneratorApplicationmain class (Unable to find a single main classinbootJar): Maven<supportingFilesToGenerate>ApiUtil.java</supportingFilesToGenerate>instead of<generateSupportingFiles>false</generateSupportingFiles>, GradleglobalProperties = [apis: '', models: '', supportingFiles: 'ApiUtil.java']. The generated<Tag>ApiControlleris a@ControllerinapiPackage: it must be under the@SpringBootApplicationpackage (e.g.com.example.demo.api), otherwise it is not scanned and the endpoints return 404.documentationProvider=noneandannotationLibrary=noneavoid pulling springdoc/swagger annotations into the generated code. Serving the spec/Swagger UI is optional: addorg.springdoc:springdoc-openapi-starter-webmvc-ui(3.x line for Boot 4, 2.8.x for Boot 3) only if requested; verified with springdoc 3.1.1 on Boot 4.1.1 (/v3/api-docsreturns OpenAPI 3.1 JSON,/swagger-ui/index.htmlreturns 200).openApiNullable=falseavoids thejackson-databind-nullabledependency; keep ittrueonly if the spec has PATCH semantics with nullable fields.Generated models use
jakarta.validation:spring-boot-starter-validationmust be on the classpath. Required properties become constructor arguments in generated order; read the generated class intarget/generated-sources/openapi(orbuild/generated/openapi) before calling constructors.Use
<importMappings>/<typeMappings>only when a schema must map to an existing class.
Step 3: Implement
One
@RestControllerper generated<Tag>Apiinterface,implementsit, no extra mapping annotations (they are inherited from the interface). Keep controllers thin; put logic in@Serviceclasses and return DTOs, not entities. Map entities to generated DTOs explicitly (a MapStruct mapper if the project already uses it).Persistence: in-memory only when asked; otherwise Spring Data JPA entities and repositories separate from the generated DTOs, PostgreSQL via Docker Compose for dev, and schema handling per the schema management rule of the
java-hibernate-jpaskill (Flyway or Liquibase for production). See thejava-springbootskill.Errors: use
@RestControllerAdviceto preserve each operation's declared error status, media type and response schema, including validation failures. HandleMethodArgumentNotValidExceptionfor request bodies and, on Boot 3.2+/4,HandlerMethodValidationExceptionfor query/path parameters; override the corresponding handlers when extendingResponseEntityExceptionHandler. Return RFC 9457ProblemDetailonly when the spec declares it; otherwise return the declared error DTO instead of Spring's default validation response. If error responses are missing or ambiguous, ask before changing the contract rather than imposing Problem Details or a blanket 400/404/409 policy.Security: map
securitySchemeswith thespring-securityskill (JWT resource server, API key filter, method security). Do not generateuseSpringSecurityPreAuthorizeunless scopes are declared.Never edit generated sources; change the spec or the generator options and rebuild.
Step 4: Test and verify
Follow the
spring-boot-testingskill:@WebMvcTestslices per controller (mock the service),@SpringBootTest+ MockMvc for the happy path and one validation failure per write operation, Testcontainers with@ServiceConnectionfor database code (seejava-testcontainers).Cover every operation in the spec: success, not found, invalid input. Test invalid constrained query/path parameters as well as invalid request bodies. For error responses, including validation failures, assert the declared status, content type and body schema, not just the status code. Optionally assert the spec itself stays valid in CI with
openapi-generator validate -i <spec>or by letting the build fail on generation errors.Run
./mvnw verifyor./gradlew build, then start the app andcurlone endpoint plus/actuator/health. Include an endpoint from a spec with a non-root server URL and assert its full path, so a missing or duplicated base prefix is caught.Report: spec issues found, generator version and options, files written, anything deferred.
Files
- ATTRIBUTION.mdAdded by AutoGineer909 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md10.9 KiB
LICENSE
MIT License Copyright GitHub, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Requirements and compatibility
Written for: GitHub Copilot
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs an API key
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- First committed by
jdubois
- Publisher
- GitHub (Official)
- Distributed by
- GitHub
- Source
- github/awesome-copilot · skills/openapi-to-application-java-spring-boot · commit 797337f
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
- Contributors
- jdubois
AutoGineer is not affiliated with or endorsed by jdubois or GitHub.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download openapi-to-application-java-spring-boot.zip