OpenAPI and Java Spring Boot with Optic
To begin using Optic with your API you first need an OpenAPI file describing your API. This YAML or JSON file can be written by hand or generated from your code. This document describes the recommended process for generating a new OpenAPI file for a Java Spring Boot projects.
We recommend using the springdoc-openapi (opens in a new tab) package to generate an OpenAPI 3 specification file from your code.
To follow along, you'll need the following tools installed:
- Git
- Java (We're using Adoptium's (opens in a new tab) OpenJDK 17.0.7+7)
- Gradle (We're using version 8.1.1)
Getting started
-
Start by cloning Spring Boot's getting start repo,
git clone https://github.com/spring-guides/gs-spring-boot
. -
Enter the "complete" directory,
cd gs-spring-boot/complete
. -
In the
build.gradle
file, insert the following line into thedependencies
section to add thespringdoc-openapi
package to the project,implementation group: 'org.springdoc', name: 'springdoc-openapi-starter-webmvc-ui', version: '2.1.0'
You should wind up with a diff similar to,
$ git diff build.gradle diff --git a/complete/build.gradle b/complete/build.gradle index 0a3df9e..d6ef80c 100644 --- a/complete/build.gradle +++ b/complete/build.gradle @@ -13,6 +13,7 @@ repositories { } dependencies { + implementation group: 'org.springdoc', name: 'springdoc-openapi-starter-webmvc-ui', version: '2.1.0' // tag::actuator[] implementation 'org.springframework.boot:spring-boot-starter-actuator' // end::actuator[]
-
Start the app,
./gradlew bootRun
. -
Once started, the app will be serving an OpenAPI 3 spec at
http://localhost:8080/v3/api-docs.yaml
(YAML), orhttp://localhost:8080/v3/api-docs
(JSON). Since Optic works by comparing OpenAPI specs across branches, you should write the file to disk (and check it into source control if this weren't a sample project):curl http://localhost:8080/v3/api-docs.yaml > openapi.yml
.
Additional package configuration details are available on SpringDocs's site (opens in a new tab).
In your own project, you may want to automate the final step of updating your openapi.yml
file with a build task, Git hook, or similar to keep the file up to date.
What's next
Automate your OpenAPI generation and test your API specifications by setting up Optic in CI.