252018Nov

Swagger Documentation With Jersey

First question, What is Swagger?

According to Wiki, Swagger is an open-source software framework backed by a large ecosystem of tools that helps developers design, build, document, and consume RESTful Web services.

Why we need Swagger

With Swagger, you can maintain your REST services effectively. It is good for both business users and UI developers to handle services. It is basically a service document for which you don’t need to write the document.

How to implement swagger?

It is easy and fast. Just put few annotations and you are good to go.

Service Class

@Path("/student")
@Produces(MediaType.APPLICATION_JSON)
public class JerseyService
{
	@Path("/{id}")
    @PUT
	@Operation(summary = "Update User",
	description = "This can only be done by the logged in user.")
	@ApiResponse(responseCode = "200", description = "User Update Success", content = @Content(schema = @Schema(implementation = Student.class)
    ))
	@ApiResponse(responseCode = "400", description = "Invalid username supplied")
	@ApiResponse(responseCode = "404", description = "User not found")
	@Tag(name="Student Services")
	public Student updateUser(
			@Parameter(description = "The user name for login", required = true) @QueryParam("username") String username,
			@Parameter(description = "Request Body Example", required = true) Student student)
	{
		return new Student();
	}here


}

Web Configuration

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>jersey</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>jersey.config.server.provider.packages</param-name>
      <param-value>io.swagger.v3.jaxrs2.integration.resources,com.swagger.jersey</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>jersey</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app>

After putting the required configuration the page will look this.

swagger-page

Download the project from this here.