auntyellow
auntyellow

Reputation: 2573

How to integrate Swagger with Pure Servlet?

My API receives following parameters:

http://hostname/api?tag_1=<value1>&tag_2=<value2>

So my Servlet looks like:

protected doGet(HttpServletRequest req, HttpServletResponse resp) {
    Map<Integer, String> paramMap = new HashMap<>();
    Enumeration<String> en = req.getParameterNames();
    while (en.hasMoreElements()) {
        String name = en.nextElement();
        if (name.startsWith("tag_")) {
            paramMap.put(Integer.parseInt(name.substring(4)), req.getParameter(name));
        }
    }
    ...
}

How can I integrate Swagger into this Servlet ?

Upvotes: 7

Views: 9391

Answers (3)

David
David

Reputation: 135

You don't have to use JAX-RS to leverage JAX-RS annotations! So you can use @Path or @Get on your servlets to drive Swagger for the documentation generation.

In addition to that, you can use the OpenAPI swagger annotations like @Operation to add more information and generate a complete documentation.

The following example generate an OpenAPI v3 specification from a Servlet:

UserServlet.java

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import java.io.IOException;

@Path("/users")
@Produces("text/plain")
public class UserServlet extends HttpServlet {

  @Override
  @GET
  @Operation(
      summary = "Return the username by id",
      parameters = {
        @Parameter(
            in = ParameterIn.QUERY,
            description = "The id of the user",
            required = true,
            name = "id",
            schema = @Schema(implementation = Integer.class))
      },
      responses = {
        @ApiResponse(
            description = "The name of the user if the user is found",
            responseCode = "200",
            content = @Content(schema = @Schema(implementation = String.class))),
        @ApiResponse(
            description = "Not found error message if the user is not found",
            responseCode = "404",
            content = @Content(schema = @Schema(implementation = String.class)))
      })
  public void doGet(
      // Tell Swagger to ignore these parameters
      @Parameter(hidden = true) HttpServletRequest req,
      @Parameter(hidden = true) HttpServletResponse resp)
      throws ServletException, IOException {
    String userIdParam = req.getParameter("id");
    // You probably want to do more argument check here
    if (userIdParam != null && Integer.parseInt(userIdParam) == 1) {
      resp.getWriter().write("Alex");
    } else {
      resp.setStatus(404);
      resp.getWriter().write("Not Found");
    }
  }
}

When scanned by Swagger, for example by using the swagger-maven-plugin, the servlet will be picked up and swagger will generate the following OpenAPI v3 yaml:

openapi.yaml

openapi: 3.0.1
paths:
  /users:
    get:
      summary: Return the username by id
      operationId: doGet
      parameters:
      - name: id
        in: query
        description: The id of the user
        required: true
        schema:
          type: integer
          format: int32
      responses:
        "200":
          description: The name of the user if the user is found
          content:
            text/plain:
              schema:
                type: string
        "404":
          description: Not found error message if the user is not found
          content:
            text/plain:
              schema:
                type: string

Upvotes: 1

martidis
martidis

Reputation: 2975

Assuming that you have swagger setup in your project, its configuration etc.

Swagger will scan your project for annotations which will result to documentation. It will use its own annotations (e.g., @Api, @ApiOperation) along with others such as @GET, @Path, @Consumes, etc.

If you have do not have annotations such as @Path, you can specify the information about the endpoints in the @ApiOperation, for example the HTTP method, the path, the params.

Upvotes: 0

Related Questions