Restful API目前是非常常见的一种构建API的信息,下面是关于jaxrs/swagger 这种常见方式的一个介绍:
- API 类
- JSON Model 类
- Filter 类
- web.xml配置
一般的API类中包含:
- Path(请求路径)
- Http Method(请求方法)
如下例: 所有的请求路径,请求参数,都是一目了然的。同时返回也是Response也是标准的jaxrs Resp
@Path("/estimates")
@com.wordnik.swagger.annotations.Api(value = "/estimates", description = "the estimates API")
public class EstimatesApi {
@GET
@Path("/price")
@com.wordnik.swagger.annotations.ApiOperation(value = "Price Estimates", notes = "The Price Estimates endpoint returns an estimated price range for each product offered at a given location. The price estimate is provided as a formatted string with the full price range and the localized currency symbol.
The response also includes low and high estimates, and the [ISO 4217](http://en.wikipedia.org/wiki/ISO_4217) currency code for situations requiring currency conversion. When surge is active for a particular product, its surge_multiplier will be greater than 1, but the price estimate already factors in this multiplier. ", response = PriceEstimate.class, responseContainer = "List")
@com.wordnik.swagger.annotations.ApiResponses(value = {
@com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "An array of price estimates by product"),
@com.wordnik.swagger.annotations.ApiResponse(code = 0, message = "Unexpected error") })
public Response estimatesPriceGet(@ApiParam(value = "Latitude component of start location.",required=true) @QueryParam("start_latitude") Double start_latitude,
@ApiParam(value = "Longitude component of start location.",required=true) @QueryParam("start_longitude") Double start_longitude,
@ApiParam(value = "Latitude component of end location.",required=true) @QueryParam("end_latitude") Double end_latitude,
@ApiParam(value = "Longitude component of end location.",required=true) @QueryParam("end_longitude") Double end_longitude)
throws NotFoundException {
// do some magic!
return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build();
}
通过注解方式构建API的JSON Model 类,每个属性通过注解描述,都是非常清楚的
@ApiModel(description = "")
public class Activities {
private Integer offset = null;
private Integer limit = null;
private Integer count = null;
private List history = new ArrayList() ;
/**
* Position in pagination.
**/
@ApiModelProperty(required = false, value = "Position in pagination.")
@JsonProperty("offset")
public Integer getOffset() {
return offset;
}
public void setOffset(Integer offset) {
this.offset = offset;
}
/**
* Number of items to retrieve (100 max).
**/
@ApiModelProperty(required = false, value = "Number of items to retrieve (100 max).")
@JsonProperty("limit")
public Integer getLimit() {
return limit;
}
public void setLimit(Integer limit) {
this.limit = limit;
}
/**
* Total number of items available.
**/
@ApiModelProperty(required = false, value = "Total number of items available.")
@JsonProperty("count")
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
/**
**/
@ApiModelProperty(required = false, value = "")
@JsonProperty("history")
public List getHistory() {
return history;
}
public void setHistory(List history) {
this.history = history;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Activities {\n");
sb.append(" offset: ").append(offset).append("\n");
sb.append(" limit: ").append(limit).append("\n");
sb.append(" count: ").append(count).append("\n");
sb.append(" history: ").append(history).append("\n");
sb.append("}\n");
return sb.toString();
}
}
使用Filter类可以定制一些过滤器,如下例:
public class ApiOriginFilter implements javax.servlet.Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
res.addHeader("Access-Control-Allow-Headers", "Content-Type");
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
上例没有做任何特殊的事情,只是给response 加了一些header
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:j2ee="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>jerseyservlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainerservlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packagesparam-name>
<param-value>com.wordnik.swagger.jaxrs.json;com.wordnik.swagger.jaxrs.listing;io.swagger.apiparam-value>
init-param>
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerRequestFiltersparam-name>
<param-value>com.sun.jersey.api.container.filter.PostReplaceFilterparam-value>
init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeatureparam-name>
<param-value>trueparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet>
<servlet-name>DefaultJaxrsConfigservlet-name>
<servlet-class>com.wordnik.swagger.jaxrs.config.DefaultJaxrsConfigservlet-class>
<init-param>
<param-name>api.versionparam-name>
<param-value>1.0.0param-value>
init-param>
<init-param>
<param-name>swagger.api.titleparam-name>
<param-value>Swagger Serverparam-value>
init-param>
<init-param>
<param-name>swagger.api.basepathparam-name>
<param-value>http://localhost:8002param-value>
init-param>
<load-on-startup>2load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>jerseyservlet-name>
<url-pattern>/*url-pattern>
servlet-mapping>
<filter>
<filter-name>ApiOriginFilterfilter-name>
<filter-class>io.swagger.api.ApiOriginFilterfilter-class>
filter>
<filter-mapping>
<filter-name>ApiOriginFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
web-app>