OpenAPI 3 Documentation With Spring Boot
Join the DZone community and get the full member experience.Join For Free
In this tutorial, we are going to try out a Spring Boot Open API 3-enabled REST project and explore some of its capabilities. Springdoc-openapi java library is fast becoming very compelling.
- Java 8.x.
- Maven 3.x.
Start by creating a Maven JAR project. Below, you will see the pom.xml to use:
Note the "springdoc-openapi-ui" dependency and "springdoc-openapi-maven-plugin" plugin.
Now, let's create a small Java bean class.
This is an example of a Java bean. Now, let's create a controller.
Above is a sample REST Controller.
Let's make some entries in src\main\resources\application.properties.
The above entries will pass on Maven build-related information to the OpenAPI documentation.
Finally, let's write the spring boot application class
Also note how the API version and description is being leveraged from application.properties.
At this stage, this is what the project looks like in Eclipse:
Above are the project contents. Next, execute the
mvn clean package from the command prompt or terminal. Then, execute
java -jar target\sample-0.0.1.jar.
You can also launch the application by running the SampleApplication.java class from your IDE.
Now, let's visit the Swagger UI — http://localhost:8080/swagger-ui.html:
Click the green Post button and expand the > symbol on the right of Person under Schemas.
The nice thing is how the contract is automatically detailed leveraging JSR-303 annotations on the model. It out-of-the-box covers many of the important annotations and documents them. However, I did not see it support out of the box
@org.hibernate.validator.constraints.CreditCardNumber at this point in time.
For completeness, let's post a request. Press the Try it out button.
Press the blue execute button.
Let's feed in a valid input:
Let's feed that valid input into the Request Body Section
On pressing the blue Execute button we see the below:
This was only a brief introduction to the capabilities of the dependency:
- Ensure prerequisites.
- If using the Eclipse IDE, we might need to do a Maven update on the project after creating all the files.
- In the Swagger UI, if you are unable to access the “Schema” definitions link, it might be because you need to come out of the “try it out “ mode. Click on one or two Cancel buttons that might be visible.
Source Code is here: https://github.com/teq-niq/sample/tree/springdoc-openapi-intro.
Git Clone URL: https://github.com/teq-niq/sample.git.
Please read part II at https://dzone.com/articles/doing-more-with-springdoc-openapi..
Also, please read part III at https://dzone.com/articles/extending-swagger-and-spring-doc-open-api.
Opinions expressed by DZone contributors are their own.