Swagger 生成RESTAPI文档的步骤

Swagger 生成RESTAPI文档的步骤,swagger,swagger-ui,Swagger,Swagger Ui,我正试图为我现有的一些RESTAPI生成基于招摇过市的RESTAPI文档(UI) 它的必要步骤或先决条件是什么?我正在Windows操作系统上工作。Swagger提供了一些关于如何构建API文档的选项 首先,您需要了解它分为两部分: CORE用于生成包含API相关信息的JSON。 此JSON遵循swagger模板 接口将读取该JSON并生成HTML 首先,您需要对控制器和端点进行注释,需要使用“swagger核心”和“swagger注释” 那么您有两个选择: a) 提供一个端点来生成和服务JSO

我正试图为我现有的一些RESTAPI生成基于招摇过市的RESTAPI文档(UI)


它的必要步骤或先决条件是什么?我正在Windows操作系统上工作。

Swagger提供了一些关于如何构建API文档的选项

首先,您需要了解它分为两部分:

CORE用于生成包含API相关信息的JSON。 此JSON遵循swagger模板

接口将读取该JSON并生成HTML

首先,您需要对控制器和端点进行注释,需要使用“swagger核心”和“swagger注释”

那么您有两个选择:

a) 提供一个端点来生成和服务JSON,并使用swagger ui读取该端点来生成HTML

b) 编译时,使用maven插件swagger maven生成JSON和HTML

更多信息,请访问:

如果你正在使用Spring,我建议你看看


如果您更喜欢Maven插件,请参见

以完成tbraun回复:

以下是清晰的演示(错误、注释等), 和

我建议你也去看医生

使用上一个版本时要小心,因为有些招摇过市的版本不支持某些招摇过市的属性,例如“apisOrder”按名称对api排序

当您测试APi时,可以使用swagger UI

我希望这将对您有所帮助。

是我们自己的库,用于与JAX-RS项目集成

我们提供了一个示例来解释如何将其与代码集成。这相当简单。还记录了这些内容,以帮助您了解应该添加哪些内容以及在何处添加

完成上述步骤后,您将得到一个
swagger.json
swagger.yaml
文件的输出。此时,您需要与应用程序集成。这样做有多种方式。一种方法是将其与您的构建过程集成,就像我们在示例中所做的那样

这两个插件的组合将为您做到这一点:

  <plugin>
    <groupId>com.googlecode.maven-download-plugin</groupId>
    <artifactId>download-maven-plugin</artifactId>
    <version>1.2.1</version>
    <executions>
      <execution>
        <id>swagger-ui</id>
        <goals>
          <goal>wget</goal>
        </goals>
        <configuration>
          <url>https://github.com/swagger-api/swagger-ui/archive/master.tar.gz</url>
          <unpack>true</unpack>
          <outputDirectory>${project.build.directory}</outputDirectory>
        </configuration>
      </execution>
    </executions>
  </plugin>
  <plugin>
    <artifactId>maven-resources-plugin</artifactId>
    <version>2.6</version>
    <executions>
      <execution>
        <id>copy-resources</id>
        <phase>validate</phase>
        <goals>
          <goal>copy-resources</goal>
        </goals>
        <configuration>
          <outputDirectory>target/${project.artifactId}-${project.version}</outputDirectory>
          <resources>
            <resource>
              <directory>${project.build.directory}/swagger-ui-master/dist</directory>
              <filtering>true</filtering>
              <excludes>
                <exclude>index.html</exclude>
              </excludes>
            </resource>
          </resources>
        </configuration>
      </execution>
    </executions>
  </plugin>

com.googlecode.maven-download-plugin
下载maven插件
1.2.1
大摇大摆的用户界面
wget
https://github.com/swagger-api/swagger-ui/archive/master.tar.gz
真的
${project.build.directory}
maven资源插件
2.6
复制资源
验证
复制资源
target/${project.artifactId}-${project.version}
${project.build.directory}/swagger ui master/dist
真的
index.html

您只需确保同时运行
目标,因此,如果您想安装它(但这取决于您的开发过程),您可以使用以下步骤:

POM

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>org.viquar./groupId>
    <artifactId>messenger</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>messenger</name>

    <build>
        <finalName>messenger</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <inherited>true</inherited>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.glassfish.jersey</groupId>
                <artifactId>jersey-bom</artifactId>
                <version>${jersey.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>


        </dependencies>
    </dependencyManagement>
    <dependencies>
        <!-- Swagger documentations -->
        <dependency>
            <groupId>com.wordnik</groupId>
            <artifactId>swagger-jersey2-jaxrs_2.10</artifactId>
            <version>1.3.12</version>
        </dependency>
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-jersey2-jaxrs</artifactId>
            <version>1.5.0</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-moxy</artifactId>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
            <version>${jersey.version}</version>
        </dependency>
    </dependencies>
    <properties>
        <jersey.version>2.16</jersey.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</project>
DataNotFoundExceptionMapper.java

package org.viquar.exception;

import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.viquar.model.ErrorMessage;

@Provider
public class DataNotFoundExceptionMapper implements ExceptionMapper<DataNotFoundException> {

    @Override
    public Response toResponse(DataNotFoundException ex) {
        ErrorMessage errorMessage = new ErrorMessage(ex.getMessage(), 404, "http://localhost:8080/JerseyRestPoc.Viquar.poc");
        return Response.status(Status.NOT_FOUND)
                .entity(errorMessage)
                .build();
    }

}
package org.viquar.exception;

import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import org.viquar.model.ErrorMessage;

// This class intentionally doesn't have the @Provider annotation.
// It has been disabled in order to try out other ways of throwing exceptions in JAX-RS

// @Provider
public class GenericExceptionMapper implements ExceptionMapper<Throwable> {

    @Override
    public Response toResponse(Throwable ex) {
        ErrorMessage errorMessage = new ErrorMessage(ex.getMessage(), 500, "http://localhost:8080/JerseyRestPoc.Viquar.poc");
        return Response.status(Status.INTERNAL_SERVER_ERROR)
                .entity(errorMessage)
                .build();
    }

}
ErrorMessage.java

package org.viquar.model;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class ErrorMessage {

    private String errorMessage;
    private int errorCode;
    private String documentation;

    public ErrorMessage() {

    }

    public ErrorMessage(String errorMessage, int errorCode, String documentation) {
        super();
        this.errorMessage = errorMessage;
        this.errorCode = errorCode;
        this.documentation = documentation;
    }
    public String getErrorMessage() {
        return errorMessage;
    }
    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }
    public int getErrorCode() {
        return errorCode;
    }
    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }
    public String getDocumentation() {
        return documentation;
    }
    public void setDocumentation(String documentation) {
        this.documentation = documentation;
    }


}
package org.viquar.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
@XmlRootElement
public class Message {

    private long id;
    private String message;
    private Date created;
    private String author;
    private Map<Long, Comment> comments = new HashMap<>();
    private List<Link> links = new ArrayList<>();

    public Message() {

    }

    public Message(long id, String message, String author) {
        this.id = id;
        this.message = message;
        this.author = author;
        this.created = new Date();
    }

    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public Date getCreated() {
        return created;
    }
    public void setCreated(Date created) {
        this.created = created;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    @XmlTransient
    public Map<Long, Comment> getComments() {
        return comments;
    }

    public void setComments(Map<Long, Comment> comments) {
        this.comments = comments;
    }

    public List<Link> getLinks() {
        return links;
    }

    public void setLinks(List<Link> links) {
        this.links = links;
    }

    public void addLink(String url, String rel) {
        Link link = new Link();
        link.setLink(url);
        link.setRel(rel);
        links.add(link);
    }


}
Link.java

package org.viquar.model;

public class Link {
    private String link;
    private String rel;

    public String getLink() {
        return link;
    }
    public void setLink(String link) {
        this.link = link;
    }
    public String getRel() {
        return rel;
    }
    public void setRel(String rel) {
        this.rel = rel;
    }


}
Message.java

package org.viquar.model;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class ErrorMessage {

    private String errorMessage;
    private int errorCode;
    private String documentation;

    public ErrorMessage() {

    }

    public ErrorMessage(String errorMessage, int errorCode, String documentation) {
        super();
        this.errorMessage = errorMessage;
        this.errorCode = errorCode;
        this.documentation = documentation;
    }
    public String getErrorMessage() {
        return errorMessage;
    }
    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }
    public int getErrorCode() {
        return errorCode;
    }
    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }
    public String getDocumentation() {
        return documentation;
    }
    public void setDocumentation(String documentation) {
        this.documentation = documentation;
    }


}
package org.viquar.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
@XmlRootElement
public class Message {

    private long id;
    private String message;
    private Date created;
    private String author;
    private Map<Long, Comment> comments = new HashMap<>();
    private List<Link> links = new ArrayList<>();

    public Message() {

    }

    public Message(long id, String message, String author) {
        this.id = id;
        this.message = message;
        this.author = author;
        this.created = new Date();
    }

    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public Date getCreated() {
        return created;
    }
    public void setCreated(Date created) {
        this.created = created;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    @XmlTransient
    public Map<Long, Comment> getComments() {
        return comments;
    }

    public void setComments(Map<Long, Comment> comments) {
        this.comments = comments;
    }

    public List<Link> getLinks() {
        return links;
    }

    public void setLinks(List<Link> links) {
        this.links = links;
    }

    public void addLink(String url, String rel) {
        Link link = new Link();
        link.setLink(url);
        link.setRel(rel);
        links.add(link);
    }


}
ProfileResource.java

package org.viquar.resources;

import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.viquar.model.Profile;
import org.viquar.service.ProfileService;

@Path("/profiles")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class ProfileResource {

    private ProfileService profileService = new ProfileService();



    @GET
    public List<Profile> getProfiles() {
        return profileService.getAllProfiles();
    }

    @POST
    public Profile addProfile(Profile profile) {
        return profileService.addProfile(profile);
    }

    @GET
    @Path("/{profileName}")
    public Profile getProfile(@PathParam("profileName") String profileName) {
        return profileService.getProfile(profileName);
    }

    @PUT
    @Path("/{profileName}")
    public Profile updateProfile(@PathParam("profileName") String profileName, Profile profile) {
        profile.setProfileName(profileName);
        return profileService.updateProfile(profile);
    }

    @DELETE
    @Path("/{profileName}")
    public void deleteProfile(@PathParam("profileName") String profileName) {
        profileService.removeProfile(profileName);
    }



}
package org.viquar.resources;

import java.net.URI;
import java.util.List;
import javax.ws.rs.BeanParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.viquar.model.Message;
import org.viquar.resources.beans.MessageFilterBean;
import org.viquar.service.MessageService;
//
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;


@Path("/messages")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Api(value = "/messages", description = "Operation about orders")
public class MessageResource {

    MessageService messageService = new MessageService();

    @GET
    public List<Message> getMessages(@BeanParam MessageFilterBean filterBean) {

        if (filterBean.getYear() > 0) {
            return messageService.getAllMessagesForYear(filterBean.getYear());
        }
        if (filterBean.getStart() >= 0 && filterBean.getSize() > 0) {
            return messageService.getAllMessagesPaginated(filterBean.getStart(), filterBean.getSize());
        }
        return messageService.getAllMessages();
    }

    @POST
    public Response addMessage(Message message, @Context UriInfo uriInfo) {

        Message newMessage = messageService.addMessage(message);
        String newId = String.valueOf(newMessage.getId());
        URI uri = uriInfo.getAbsolutePathBuilder().path(newId).build();
        return Response.created(uri)
                .entity(newMessage)
                .build();
    }

    @PUT
    @Path("/{messageId}")
    public Message updateMessage(@PathParam("messageId") long id, Message message) {
        message.setId(id);
        return messageService.updateMessage(message);
    }

    @DELETE
    @Path("/{messageId}")
    public void deleteMessage(@PathParam("messageId") long id) {
        messageService.removeMessage(id);
    }


    @GET
    @Path("/{messageId}")
    @ApiOperation(value = "Returns user details", notes = "Returns a complete list of users details with a date of last modification.", response = Message.class)
    @ApiResponses(value = {
        @ApiResponse(code = 200, message = "Successful retrieval of user detail", response = Message.class),
        @ApiResponse(code = 404, message = "User with given username does not exist"),
        @ApiResponse(code = 500, message = "Internal server error")
        })
    public Message getMessage(@PathParam("messageId") long id, @Context UriInfo uriInfo) {
        Message message = messageService.getMessage(id);
        message.addLink(getUriForSelf(uriInfo, message), "self");
        message.addLink(getUriForProfile(uriInfo, message), "profile");
        message.addLink(getUriForComments(uriInfo, message), "comments");

        return message;

    }

    private String getUriForComments(UriInfo uriInfo, Message message) {
        URI uri = uriInfo.getBaseUriBuilder()
                .path(MessageResource.class)
                .path(MessageResource.class, "getCommentResource")
                .path(CommentResource.class)
                .resolveTemplate("messageId", message.getId())
                .build();
        return uri.toString();
    }

    private String getUriForProfile(UriInfo uriInfo, Message message) {
        URI uri = uriInfo.getBaseUriBuilder()
             .path(ProfileResource.class)
             .path(message.getAuthor())
             .build();
        return uri.toString();
    }

    private String getUriForSelf(UriInfo uriInfo, Message message) {
        String uri = uriInfo.getBaseUriBuilder()
         .path(MessageResource.class)
         .path(Long.toString(message.getId()))
         .build()
         .toString();
        return uri;
    }




    @Path("/{messageId}/comments")
    public CommentResource getCommentResource() {
        return new CommentResource();
    }

}
package org.viquar.resources;

import javax.ws.rs.Consumes;
import javax.ws.rs.CookieParam;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.MatrixParam;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;

@Path("/injectdemo")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public class InjectDemoResource {

    @GET
    @Path("annotations")
    public String getParamsUsingAnnotations(@MatrixParam("param") String matrixParam,
                                            @HeaderParam("authSessionID") String header,
                                            @CookieParam("name") String cookie) {
        return "Matrix param: " + matrixParam + " Header param: " + header + " Cookie param: " + cookie;
    }

    @GET
    @Path("context")
    public String getParamsUsingContext(@Context UriInfo uriInfo, @Context HttpHeaders headers) {

        String path = uriInfo.getAbsolutePath().toString();
        String cookies = headers.getCookies().toString();
        return "Path : " + path + " Cookies: " + cookies;
    }




}
package org.viquar.resources;

import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.viquar.model.Comment;
import org.viquar.service.CommentService;

@Path("/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)

public class CommentResource {

    private CommentService commentService = new CommentService();

    @GET
    public List<Comment> getAllComments(@PathParam("messageId") long messageId) {
        return commentService.getAllComments(messageId);
    }

    @POST
    public Comment addComment(@PathParam("messageId") long messageId, Comment comment) {
        return commentService.addComment(messageId, comment);
    }

    @PUT
    @Path("/{commentId}")
    public Comment updateComment(@PathParam("messageId") long messageId, @PathParam("commentId") long id, Comment comment) {
        comment.setId(id);
        return commentService.updateComment(messageId, comment);
    }

    @DELETE
    @Path("/{commentId}")
    public void deleteComment(@PathParam("messageId") long messageId, @PathParam("commentId") long commentId) {
        commentService.removeComment(messageId, commentId);
    }


    @GET
    @Path("/{commentId}")
    public Comment getMessage(@PathParam("messageId") long messageId, @PathParam("commentId") long commentId) {
        return commentService.getComment(messageId, commentId);
    }

}
CommentResource.java

package org.viquar.resources;

import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.viquar.model.Profile;
import org.viquar.service.ProfileService;

@Path("/profiles")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class ProfileResource {

    private ProfileService profileService = new ProfileService();



    @GET
    public List<Profile> getProfiles() {
        return profileService.getAllProfiles();
    }

    @POST
    public Profile addProfile(Profile profile) {
        return profileService.addProfile(profile);
    }

    @GET
    @Path("/{profileName}")
    public Profile getProfile(@PathParam("profileName") String profileName) {
        return profileService.getProfile(profileName);
    }

    @PUT
    @Path("/{profileName}")
    public Profile updateProfile(@PathParam("profileName") String profileName, Profile profile) {
        profile.setProfileName(profileName);
        return profileService.updateProfile(profile);
    }

    @DELETE
    @Path("/{profileName}")
    public void deleteProfile(@PathParam("profileName") String profileName) {
        profileService.removeProfile(profileName);
    }



}
package org.viquar.resources;

import java.net.URI;
import java.util.List;
import javax.ws.rs.BeanParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.viquar.model.Message;
import org.viquar.resources.beans.MessageFilterBean;
import org.viquar.service.MessageService;
//
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;


@Path("/messages")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Api(value = "/messages", description = "Operation about orders")
public class MessageResource {

    MessageService messageService = new MessageService();

    @GET
    public List<Message> getMessages(@BeanParam MessageFilterBean filterBean) {

        if (filterBean.getYear() > 0) {
            return messageService.getAllMessagesForYear(filterBean.getYear());
        }
        if (filterBean.getStart() >= 0 && filterBean.getSize() > 0) {
            return messageService.getAllMessagesPaginated(filterBean.getStart(), filterBean.getSize());
        }
        return messageService.getAllMessages();
    }

    @POST
    public Response addMessage(Message message, @Context UriInfo uriInfo) {

        Message newMessage = messageService.addMessage(message);
        String newId = String.valueOf(newMessage.getId());
        URI uri = uriInfo.getAbsolutePathBuilder().path(newId).build();
        return Response.created(uri)
                .entity(newMessage)
                .build();
    }

    @PUT
    @Path("/{messageId}")
    public Message updateMessage(@PathParam("messageId") long id, Message message) {
        message.setId(id);
        return messageService.updateMessage(message);
    }

    @DELETE
    @Path("/{messageId}")
    public void deleteMessage(@PathParam("messageId") long id) {
        messageService.removeMessage(id);
    }


    @GET
    @Path("/{messageId}")
    @ApiOperation(value = "Returns user details", notes = "Returns a complete list of users details with a date of last modification.", response = Message.class)
    @ApiResponses(value = {
        @ApiResponse(code = 200, message = "Successful retrieval of user detail", response = Message.class),
        @ApiResponse(code = 404, message = "User with given username does not exist"),
        @ApiResponse(code = 500, message = "Internal server error")
        })
    public Message getMessage(@PathParam("messageId") long id, @Context UriInfo uriInfo) {
        Message message = messageService.getMessage(id);
        message.addLink(getUriForSelf(uriInfo, message), "self");
        message.addLink(getUriForProfile(uriInfo, message), "profile");
        message.addLink(getUriForComments(uriInfo, message), "comments");

        return message;

    }

    private String getUriForComments(UriInfo uriInfo, Message message) {
        URI uri = uriInfo.getBaseUriBuilder()
                .path(MessageResource.class)
                .path(MessageResource.class, "getCommentResource")
                .path(CommentResource.class)
                .resolveTemplate("messageId", message.getId())
                .build();
        return uri.toString();
    }

    private String getUriForProfile(UriInfo uriInfo, Message message) {
        URI uri = uriInfo.getBaseUriBuilder()
             .path(ProfileResource.class)
             .path(message.getAuthor())
             .build();
        return uri.toString();
    }

    private String getUriForSelf(UriInfo uriInfo, Message message) {
        String uri = uriInfo.getBaseUriBuilder()
         .path(MessageResource.class)
         .path(Long.toString(message.getId()))
         .build()
         .toString();
        return uri;
    }




    @Path("/{messageId}/comments")
    public CommentResource getCommentResource() {
        return new CommentResource();
    }

}
package org.viquar.resources;

import javax.ws.rs.Consumes;
import javax.ws.rs.CookieParam;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.MatrixParam;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;

@Path("/injectdemo")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public class InjectDemoResource {

    @GET
    @Path("annotations")
    public String getParamsUsingAnnotations(@MatrixParam("param") String matrixParam,
                                            @HeaderParam("authSessionID") String header,
                                            @CookieParam("name") String cookie) {
        return "Matrix param: " + matrixParam + " Header param: " + header + " Cookie param: " + cookie;
    }

    @GET
    @Path("context")
    public String getParamsUsingContext(@Context UriInfo uriInfo, @Context HttpHeaders headers) {

        String path = uriInfo.getAbsolutePath().toString();
        String cookies = headers.getCookies().toString();
        return "Path : " + path + " Cookies: " + cookies;
    }




}
package org.viquar.resources;

import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.viquar.model.Comment;
import org.viquar.service.CommentService;

@Path("/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)

public class CommentResource {

    private CommentService commentService = new CommentService();

    @GET
    public List<Comment> getAllComments(@PathParam("messageId") long messageId) {
        return commentService.getAllComments(messageId);
    }

    @POST
    public Comment addComment(@PathParam("messageId") long messageId, Comment comment) {
        return commentService.addComment(messageId, comment);
    }

    @PUT
    @Path("/{commentId}")
    public Comment updateComment(@PathParam("messageId") long messageId, @PathParam("commentId") long id, Comment comment) {
        comment.setId(id);
        return commentService.updateComment(messageId, comment);
    }

    @DELETE
    @Path("/{commentId}")
    public void deleteComment(@PathParam("messageId") long messageId, @PathParam("commentId") long commentId) {
        commentService.removeComment(messageId, commentId);
    }


    @GET
    @Path("/{commentId}")
    public Comment getMessage(@PathParam("messageId") long messageId, @PathParam("commentId") long commentId) {
        return commentService.getComment(messageId, commentId);
    }

}
CommentService.java

package org.viquar.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.viquar.database.DatabaseClass;
import org.viquar.model.Comment;
import org.viquar.model.ErrorMessage;
import org.viquar.model.Message;

public class CommentService {

    private Map<Long, Message> messages = DatabaseClass.getMessages();

    public List<Comment> getAllComments(long messageId) {
        Map<Long, Comment> comments = messages.get(messageId).getComments();
        return new ArrayList<Comment>(comments.values());
    }

    public Comment getComment(long messageId, long commentId) {
        ErrorMessage errorMessage = new ErrorMessage("Not found", 404, "http://CosineOTC.Viquar.poc");
        Response response = Response.status(Status.NOT_FOUND)
                .entity(errorMessage)
                .build();

        Message message = messages.get(messageId);
        if (message == null) {
            throw new WebApplicationException(response);
        }
        Map<Long, Comment> comments = messages.get(messageId).getComments();
        Comment comment = comments.get(commentId);
        if (comment == null) {
            throw new NotFoundException(response);
        }
        return comment;
    }

    public Comment addComment(long messageId, Comment comment) {
        Map<Long, Comment> comments = messages.get(messageId).getComments();
        comment.setId(comments.size() + 1);
        comments.put(comment.getId(), comment);
        return comment;
    }




    public Comment updateComment(long messageId, Comment comment) {
        Map<Long, Comment> comments = messages.get(messageId).getComments();
        if (comment.getId() <= 0) {
            return null;
        }
        comments.put(comment.getId(), comment);
        return comment;
    }

    public Comment removeComment(long messageId, long commentId) {
        Map<Long, Comment> comments = messages.get(messageId).getComments();
        return comments.remove(commentId);
    }

}
package org.viquar.service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import org.viquar.database.DatabaseClass;
import org.viquar.exception.DataNotFoundException;
import org.viquar.model.Message;

public class MessageService {

    private Map<Long, Message> messages = DatabaseClass.getMessages();

    public MessageService() {
        messages.put(1L, new Message(1, "Hello World", "ViquarKhan"));
        messages.put(2L, new Message(2, "Hello Jersey", "Shahbazkhan"));
        messages.put(3L, new Message(3, "Hello Cosine", "Snehaghosh"));
    }

    public List<Message> getAllMessages() {
        return new ArrayList<Message>(messages.values()); 
    }

    public List<Message> getAllMessagesForYear(int year) {
        List<Message> messagesForYear = new ArrayList<>();
        Calendar cal = Calendar.getInstance();
        for (Message message : messages.values()) {
            cal.setTime(message.getCreated());
            if (cal.get(Calendar.YEAR) == year) {
                messagesForYear.add(message);
            }
        }
        return messagesForYear;
    }

    public List<Message> getAllMessagesPaginated(int start, int size) {
        ArrayList<Message> list = new ArrayList<Message>(messages.values());
        if (start + size > list.size()) return new ArrayList<Message>();
        return list.subList(start, start + size); 
    }


    public Message getMessage(long id) {
        Message message = messages.get(id);
        if (message == null) {
            throw new DataNotFoundException("Message with id " + id + " not found");
        }
        return message;
    }

    public Message addMessage(Message message) {
        message.setId(messages.size() + 1);
        messages.put(message.getId(), message);
        return message;
    }

    public Message updateMessage(Message message) {
        if (message.getId() <= 0) {
            return null;
        }
        messages.put(message.getId(), message);
        return message;
    }

    public Message removeMessage(long id) {
        return messages.remove(id);
    }
}
package org.viquar.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.viquar.database.DatabaseClass;
import org.viquar.model.Profile;

public class ProfileService {

    private Map<String, Profile> profiles = DatabaseClass.getProfiles();

    public ProfileService() {
        profiles.put("Viquar", new Profile(1L, "Viquar", "Viquar", "Khan"));
        profiles.put("Shahbaz", new Profile(2L, "Shahbaz", "Shahbaz", "Khan"));
        profiles.put("Sneha", new Profile(3L, "Sneha", "Sneha", "Ghosh"));
    }

    public List<Profile> getAllProfiles() {
        return new ArrayList<Profile>(profiles.values()); 
    }

    public Profile getProfile(String profileName) {
        return profiles.get(profileName);
    }

    public Profile addProfile(Profile profile) {
        profile.setId(profiles.size() + 1);
        profiles.put(profile.getProfileName(), profile);
        return profile;
    }

    public Profile updateProfile(Profile profile) {
        if (profile.getProfileName().isEmpty()) {
            return null;
        }
        profiles.put(profile.getProfileName(), profile);
        return profile;
    }

    public Profile removeProfile(String profileName) {
        return profiles.remove(profileName);
    }

}

由于限制问题,下一条评论继续…

第2部分继续

现在,您必须配置Webapp,创建具有以下名称的文件夹,并将内容复制到该文件夹中

  • 在Jerseyrestsweggerpoc\src\main\webapp\CSS中复制CSS

  • 复制Jerseyrestsweggerpoc\src\main\webapp\font中的字体

  • 复制Jerseyrestsweggerpoc\src\main\webapp\images内的图像

  • 在Jerseyrestsweggerpoc\src\main\webapp\lang中复制lang

  • 复制Jerseyrestsweggerpoc\src\main\webapp\lib中的库

index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Swagger UI</title>
  <link rel="icon" type="image/png" href="images/favicon-32x32.png" sizes="32x32" />
  <link rel="icon" type="image/png" href="images/favicon-16x16.png" sizes="16x16" />
  <link href='css/typography.css' media='screen' rel='stylesheet' type='text/css'/>
  <link href='css/reset.css' media='screen' rel='stylesheet' type='text/css'/>
  <link href='css/screen.css' media='screen' rel='stylesheet' type='text/css'/>
  <link href='css/reset.css' media='print' rel='stylesheet' type='text/css'/>
  <link href='css/print.css' media='print' rel='stylesheet' type='text/css'/>
  <script src='lib/jquery-1.8.0.min.js' type='text/javascript'></script>
  <script src='lib/jquery.slideto.min.js' type='text/javascript'></script>
  <script src='lib/jquery.wiggle.min.js' type='text/javascript'></script>
  <script src='lib/jquery.ba-bbq.min.js' type='text/javascript'></script>
  <script src='lib/handlebars-2.0.0.js' type='text/javascript'></script>
  <script src='lib/underscore-min.js' type='text/javascript'></script>
  <script src='lib/backbone-min.js' type='text/javascript'></script>
  <script src='swagger-ui.js' type='text/javascript'></script>
  <script src='lib/highlight.7.3.pack.js' type='text/javascript'></script>
  <script src='lib/marked.js' type='text/javascript'></script>
  <script src='lib/swagger-oauth.js' type='text/javascript'></script>

  <!-- Some basic translations -->
  <!-- <script src='lang/translator.js' type='text/javascript'></script> -->
  <!-- <script src='lang/ru.js' type='text/javascript'></script> -->
  <!-- <script src='lang/en.js' type='text/javascript'></script> -->

  <script type="text/javascript">
    $(function () {
      var url = window.location.search.match(/url=([^&]+)/);
      if (url && url.length > 1) {
        url = decodeURIComponent(url[1]);
      } else {
        url = "http://localhost:8080/messenger/api/v1/api-docs";
      }

      // Pre load translate...
      if(window.SwaggerTranslator) {
        window.SwaggerTranslator.translate();
      }
      window.swaggerUi = new SwaggerUi({
        url: url,
        dom_id: "swagger-ui-container",
        supportedSubmitMethods: ['get', 'post', 'put', 'delete', 'patch'],
        onComplete: function(swaggerApi, swaggerUi){
          if(typeof initOAuth == "function") {
            initOAuth({
              clientId: "your-client-id",
              clientSecret: "your-client-secret",
              realm: "your-realms",
              appName: "your-app-name", 
              scopeSeparator: ","
            });
          }

          if(window.SwaggerTranslator) {
            window.SwaggerTranslator.translate();
          }

          $('pre code').each(function(i, e) {
            hljs.highlightBlock(e)
          });

          addApiKeyAuthorization();
        },
        onFailure: function(data) {
          log("Unable to Load SwaggerUI");
        },
        docExpansion: "none",
        apisSorter: "alpha",
        showRequestHeaders: false
      });

      function addApiKeyAuthorization(){
        var key = encodeURIComponent($('#input_apiKey')[0].value);
        if(key && key.trim() != "") {
            var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("api_key", key, "query");
            window.swaggerUi.api.clientAuthorizations.add("api_key", apiKeyAuth);
            log("added key " + key);
        }
      }

      $('#input_apiKey').change(addApiKeyAuthorization);

      // if you have an apiKey you would like to pre-populate on the page for demonstration purposes...
      /*
        var apiKey = "myApiKeyXXXX123456789";
        $('#input_apiKey').val(apiKey);
      */

      window.swaggerUi.load();

      function log() {
        if ('console' in window) {
          console.log.apply(console, arguments);
        }
      }
  });
  </script>
</head>

<body class="swagger-section">
<div id='header'>
  <div class="swagger-ui-wrap">
    <a id="logo" href="http://swagger.io">swagger</a> -->
    <form id='api_selector'>
      <div class='input'><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl" type="text"/></div>
      <div class='input'><input placeholder="api_key" id="input_apiKey" name="apiKey" type="text"/></div>
      <div class='input'><a id="explore" href="#" data-sw-translate>Explore</a></div>
    </form>
  </div>
</div>

<div id="message-bar" class="swagger-ui-wrap" data-sw-translate>&nbsp;</div>
<div id="swagger-ui-container" class="swagger-ui-wrap"></div>
</body>
</html>
在MessageResource.java内部,我为Swagger添加了以下注释


@Api(value=“/messages”,description=“关于订单的操作”)

您需要提供更多详细信息。你是否有一个现有的API,或者你正在寻找设计一个?如果您有一个现有的API,那么您使用哪种开发语言和框架/库?我有一个现有的API,使用JAX-RS和Maven上的Jersey Libs设计。我需要一些步骤来生成基于招摇的UI.pom.xml。刚刚更新了插件配置,指向UI的主版本。信息不足。那是什么时候?完整的pom.xml是什么?插件应该以
目标执行。你偏离了原来的问题,很难在评论中全部回答。欢迎向我们的谷歌小组发送帖子。您好,我成功构建了maven!json是在哪里创建的?它不是创建的,而是在运行时生成的。它将托管在应用程序的上下文根目录中。存储库中到处都有这样的记录,你已经达到了极限这一事实应该暗示你的答案太长了。在这方面,我们期望得到完整、但又简短的答案,以回答手头的具体问题。这条规则有一些例外,但事实并非如此。
<html>
<head> 
   <meta charset="UTF-8"> 
   <title>Swagger UI</title> 
   <link rel="icon" type="image/png" href="images/favicon-32x32.png" sizes="32x32" /> 
   <link rel="icon" type="image/png" href="images/favicon-16x16.png" sizes="16x16" /> 
   <link href='css/typography.css' media='screen' rel='stylesheet' type='text/css'/> 
   <link href='css/reset.css' media='screen' rel='stylesheet' type='text/css'/> 
   <link href='css/screen.css' media='screen' rel='stylesheet' type='text/css'/> 
   <link href='css/reset.css' media='print' rel='stylesheet' type='text/css'/> 
   <link href='css/print.css' media='print' rel='stylesheet' type='text/css'/> 
   <script src='lib/jquery-1.8.0.min.js' type='text/javascript'></script> 
   <script src='lib/jquery.slideto.min.js' type='text/javascript'></script> 
   <script src='lib/jquery.wiggle.min.js' type='text/javascript'></script> 
   <script src='lib/jquery.ba-bbq.min.js' type='text/javascript'></script> 
   <script src='lib/handlebars-2.0.0.js' type='text/javascript'></script> 
   <script src='lib/underscore-min.js' type='text/javascript'></script> 
   <script src='lib/backbone-min.js' type='text/javascript'></script> 
   <script src='swagger-ui.js' type='text/javascript'></script> 
   <script src='lib/highlight.7.3.pack.js' type='text/javascript'></script> 
   <script src='lib/marked.js' type='text/javascript'></script> 
   <script src='lib/swagger-oauth.js' type='text/javascript'></script> 

   <!-- Some basic translations --> 
   <!-- <script src='lang/translator.js' type='text/javascript'></script> --> 
   <!-- <script src='lang/ru.js' type='text/javascript'></script> --> 
   <!-- <script src='lang/en.js' type='text/javascript'></script> --> 


   <script type="text/javascript"> 
     $(function () { 
       var url = window.location.search.match(/url=([^&]+)/); 
       if (url && url.length > 1) { 
         url = decodeURIComponent(url[1]); 
       } else { 
         url = "http://petstore.swagger.io/v2/swagger.json"; 
       } 

       // Pre load translate... 
       if(window.SwaggerTranslator) { 
         window.SwaggerTranslator.translate(); 
       } 
       window.swaggerUi = new SwaggerUi({ 
         url: url, 
         dom_id: "swagger-ui-container", 
         supportedSubmitMethods: ['get', 'post', 'put', 'delete', 'patch'], 
         onComplete: function(swaggerApi, swaggerUi){ 
           if(typeof initOAuth == "function") { 
             initOAuth({ 
               clientId: "your-client-id", 
               clientSecret: "your-client-secret", 
               realm: "your-realms", 
               appName: "your-app-name",  
               scopeSeparator: "," 
             }); 
           } 

           if(window.SwaggerTranslator) { 
             window.SwaggerTranslator.translate(); 
           } 

           $('pre code').each(function(i, e) { 
             hljs.highlightBlock(e) 
           }); 

           addApiKeyAuthorization(); 
         }, 
         onFailure: function(data) { 
           log("Unable to Load SwaggerUI"); 
         }, 
         docExpansion: "none", 
         apisSorter: "alpha", 
         showRequestHeaders: false 
       }); 

       function addApiKeyAuthorization(){ 
         var key = encodeURIComponent($('#input_apiKey')[0].value); 
         if(key && key.trim() != "") { 
             var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("api_key", key, "query"); 
             window.swaggerUi.api.clientAuthorizations.add("api_key", apiKeyAuth); 
             log("added key " + key); 
         } 
       } 

       $('#input_apiKey').change(addApiKeyAuthorization); 

       // if you have an apiKey you would like to pre-populate on the page for demonstration purposes... 
       /* 
         var apiKey = "myApiKeyXXXX123456789"; 
         $('#input_apiKey').val(apiKey); 
       */ 

       window.swaggerUi.load(); 

       function log() { 
         if ('console' in window) { 
           console.log.apply(console, arguments); 
         } 
       } 
   }); 
   </script> 
 </head> 

<body>
    <h2>Jersey RESTful Web Application!</h2>
    <p><a href="webapi/myresource">Jersey resource</a>
    <p>Visit <a href="http://jersey.java.net">Project Jersey website</a>
    for more information on Jersey!



</body>
</html>
<script>
var qp = null;
if(window.location.hash) {
  qp = location.hash.substring(1);
}
else {
  qp = location.search.substring(1);
}
qp = qp ? JSON.parse('{"' + qp.replace(/&/g, '","').replace(/=/g,'":"') + '"}',
  function(key, value) {
    return key===""?value:decodeURIComponent(value) }
  ):{}

if (window.opener.swaggerUi.tokenUrl)
    window.opener.processOAuthCode(qp);
else
    window.opener.onOAuthComplete(qp);

window.close();
</script>
http://localhost:8080/messenger//api/v1/messages/1
**Swegger** :
http://localhost:8080/messenger/
http://localhost:8080/jersey-swagger/rest/api-docs
http://localhost:8080/jersey-swagger/#!/employees/createEmployee




http://localhost:8080/messenger//api/v1/api-docs
http://localhost:8080/messenger/#!/messages/getMessage
http://localhost:8080/messenger//api/v1/messages/1


{
"author":"Viquar Khan","created":"2015-07-31T16:35:43.498",
"id":1,
"links":[
{"link":"http://localhost:8080/JerseyRestPoc//api/v1/messages/1","rel":"self"},
{"http://localhost:8080/JerseyRestPoc//api/v1/profiles/Viquar%20Khan","rel":"profile"},
{"link":"http://localhost:8080/JerseyRestPoc/api/v1/messages/1/comments/","rel":"comments"}
],
"message":"Hello World"
}