spring boot example with swagger
To create a Spring Boot example with Swagger, follow these steps:
- Add Swagger dependencies to your project's
pom.xml
file: - Add the
springfox-swagger2
andspringfox-swagger-ui
dependencies. These dependencies will enable Swagger support in your Spring Boot application.
Create a Swagger configuration class:
- Create a new Java class and annotate it with
@Configuration
to indicate that it is a configuration class. - Annotate the class with
@EnableSwagger2
to enable Swagger in your Spring Boot application. - Create a bean of type
Docket
to configure Swagger settings. Customize the Docket bean according to your requirements. For example, you can set the base package for scanning API classes using the
basePackage
method.Annotate your API classes with Swagger annotations:
- Add Swagger annotations to your REST controller classes and methods.
- Use
@Api
annotation on the class level to provide a description for the API. - Use
@ApiOperation
annotation on the method level to provide a description for each API operation. Use
@ApiParam
annotation to provide descriptions for method parameters.Build and run your Spring Boot application:
- Build your application using your preferred build tool, such as Maven or Gradle.
Run your application using a command-line tool or an IDE.
Access Swagger UI:
- Open a web browser and navigate to
http://localhost:8080/swagger-ui.html
. - This will display the Swagger UI interface, where you can explore and test your APIs.
That's it! You have successfully created a Spring Boot example with Swagger. Swagger will generate API documentation based on the annotations you added to your API classes and methods, making it easier to understand and test your APIs.