In this blog post, we’ll discover how to set up Swagger with our applications while generating documentation to Web Services using Swagger annotations and integrating Swagger UI.
But before we begin, what is Swagger and what does it do?
Swagger, often defined as the world’s largest framework of API developer tools for the OpenAPI Specification, enables development across the entire API lifecycle – from design and documentation, to test and deployment. For the ones who aren’t aware of Swagger’s popularity, here are a few reasons why:
- Swagger generates an interactive API console for people to quickly learn about and try the API.
- Swagger generates the client SDK code needed for implementations on various platforms.
- The Swagger file can be auto-generated from code annotations on several different platforms.
- Swagger has a strong community with helpful contributors.
The Swagger specifications provide a way to describe your API using a specific JSON or YAML schema that outlines the names, order, and other details of the API.
You can code this Swagger file by hand in a text editor, or you can auto-generate it from annotations in your source code. Different tools can consume the Swagger file to generate the interactive API documentation.
What are we discussing now?
- Integrating Swagger for your project
- Generating Swagger documentation using annotations
Integrating Swagger for your project
Go ahead and complete the following three steps for integration Swagger with your application.
- Adding the dependencies to your application
- Hooking up Swagger-Core in your application
- Configure and initialize Swagger
Step-1:
Add maven dependency in our pom.xml file:
1 2 3 4 5 |
<dependency> <groupId>io.swagger</groupId> <artifactId>swagger-jaxrs</artifactId> <version>1.5.0</version> </dependency> |
Step-2:
Hooking up Swagger-Core in your application:
When you use Jersey’s ServletContainer servlet, you can either configure it using the web.xml directly or use a custom application subclass. Follow the instructions below based on the configuration you use in your application:
- Package scanning/Concrete class selection
- Using a custom Application subclass
In this example, we are using package scanning approach.
If we are defining it as a servlet:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<servlet> <servlet-name>Jersey Web Application</servlet-name> <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> <init-param> <param-name>jersey.config.server.provider.packages</param-name> <param-value>com.wavelabs.resource,io.swagger.jaxrs.listing</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Jersey Web Application</servlet-name> <url-pattern>/care/*</url-pattern> </servlet-mapping> |
In the above code, com.wavelabs.resource is my application package name, you can change it to your application package name.
If we are defining as a Filter:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<filter> <filter-name>jersey</filter-name> <filter-class>org.glassfish.jersey.servlet.ServletContainer</filter-class> <init-param> <param-name>jersey.config.server.provider.packages</param-name> <param-value> io.swagger.jaxrs.listing, {your.application.packages} </param-value> </init-param> </filter> <filter-mapping> <filter-name>jersey</filter-name> <url-pattern>/api/*</url-pattern> </filter-mapping> |
Step-3:
- Configure and initialize Swagger
There are two main ways to configure and initialize the Swagger definition within your application. The first, within the web.xml, offers a simplified method of configuration. If you’re looking for more control, then the BeanConfig path is the one you should choose.
- Using Swagger’s Servlet in the web.xml
- Using Swagger’s BeanConfig
- Using a Servlet
- Using the Application class
In this example, we are following BeanConfig using Servlet approach.
Create a Servlet like below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class SwaggerConfiguration extends HttpServlet{ public void init(ServletConfig config) throws ServletException { super.init(config); BeanConfig beanConfig = new BeanConfig(); beanConfig.setTitle("Search engine"); beanConfig.setVersion("1.0"); beanConfig.setSchemes(new String[]{"http"}); beanConfig.setHost("localhost:8080"); beanConfig.setBasePath("/Search/care"); beanConfig.setResourcePackage("com.wavelabs.resource"); beanConfig.setScan(true); beanConfig.setDescription("Faster full text search engine"); } } |
Map the Servlet in web.xml file
1 2 3 4 5 |
<servlet> <servlet-name>SwaggerBootstrap</servlet-name> <servlet-class>com.wavelabs.swagger.config.SwaggerConfiguration</servlet-class> <load-on-startup>2</load-on-startup> </servlet> |
On completion of the above three steps, your application is configured with Swagger.
To see swagger.json file, hit the URL:
http://localhost:8080/ApplicationContext/swagger.json
In this example, the application context is ‘Search’, and in web.xml I have mentioned /care/* as a URL pattern. So the url is : http://localhost:8080/Search/care/swagger.json
By clicking on this URL, you should be able to see properties set in the BeanConfig servlet.
Generating swagger documentation using annotations.
To generate Documentation with Swagger, We need to use swagger annotations.
Here is an example resource defined with swagger annotations.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
@Path("/solr") @Api(value="/", desolrscription="Operations on the Solr server" ) public class SolrResource { @GET @Path("reindex") @Produces(MediaType.APPLICATION_JSON) @ApiResponses(value= { @ApiResponse(code=200, message="Solr re indexing completed successfully"), @ApiResponse(code=500, message="Error occurred in server"), }) @ApiOperation(value=" Performs re index operation on solr") public Response reIndex() { //Code return Response.ok(message).build(); } } |
@Api(Should required): Marks a class as a Swagger resource
@ApiOperation: Describes an operation or typically an HTTP method against a specific path.
@ApiResponses: Describes a possible response to an operation.
@ApiResponses: A wrapper to allow a list of multiple APIResponse objects.
To learn more about annotations use this link
After adding annotations to your web services, reload your application on server, and then visit
http://localhost:8080/Search/care/swagger.json or
http://localhost:8080/Search/care/swagger.yaml
You see the similar JSON data like this:
If we hit the URL in browser, the data comes in a JSON format.
Steps to set-up Swagger UI:
- Check out the dist folder of the swagger-UI source code from Github.
- Copy all the files and folders as is from the dist folder into our REST API service folder src/main/webapp/
- Now edit the index.html file and replace the pet store URL http://petstore.swagger.io/v2/swagger.json with our API spec URL: http://localhost:8080/Search/care/swagger.json (in your case you need to include your URL.)
- Go to http://localhost:8080/Search/index.html and you will see the page displayed as shown below:
Usually we have an index.html page as landing page to the application. So rename it to the swagger.html
So your application URL is: http://localhost:8080/ApplicationContext/swagger.html
In my example, it will look like http://localhost:8080/Search/swagger.html.
And that’s it, you’re done with Swagger!