官术网_书友最值得收藏!

Advancing the REST API

This API will be far more useful and will provide us with the ability to add data so that the current web data feed is not the only data source.

The sample code in the georestwebservice project (of this chapter) is an updated version of the API with the new recordFeature method in the georestwebservice.dart file:

 @ApiMethod(path: 'record', method: 'POST')
QuakeResponse recordFeature(QuakeRequest request) {
  DaoQuakeAPI quakeAPI = new DaoQuakeAPI();
  quakeAPI.recordFeature(getFeatureAsJSON(request));

  QuakeResponse quakeResponse = new QuakeResponse();
  quakeResponse.result = "1";

  return quakeResponse;
}

This method will use the standard HTTP POST verb in order to receive the input from the client application. As the rpc package wraps the entire method and composes and sends error responses, there is no need for error handling in this method. If, for example, something goes wrong while storing a result in the database, the client will receive an error message.

The following getFeatureAsJSON function, that is found in the helpers.dart file, converts the incoming QuakeRequest object into a JSON string:

String getFeatureAsJSON(QuakeRequest request) {
  String feature = jsonData;
  feature = feature.replaceAll("MAG", request.magnitude.toString());
  feature = feature.replaceFirst("TIME", request.time.toString());
  feature = feature.replaceFirst("LAT", request.latitude.toString());
  feature = feature.replaceFirst("LONG", request.longitude.toString());
  return feature;
}

The jsonData string is a template for the GeoJSON feature. The String class has numerous useful methods that are used to match strings, and these are used to generate the final string that is returned from the function. The replaceAll method is used to replace every occurrence of a string; in this case, for the magnitude that appears as a value and in the text description. The replaceFirst method is used to replace the first occurrence of a string and is used in this function for the values that appear only once in the string.

The following API method's parameter is a simple class that is declared in the same file that contains four fields:

class QuakeRequest {

  @ApiProperty(required: true)
  int time;

  @ApiProperty(required: true)
  double magnitude;

  @ApiProperty(required: true)
  double longitude;

  @ApiProperty(required: true)
  double latitude;
}

The fields are annotated, which allows the rpc package to handle the marshaling of data through the REST interface.

主站蜘蛛池模板: 山东省| 黔江区| 游戏| 阳江市| 南木林县| 延寿县| 吉安市| 潮州市| 宿松县| 湖口县| 奉新县| 蒙山县| 广汉市| 洞口县| 当阳市| 泰宁县| 长春市| 永宁县| 什邡市| 凤台县| 怀来县| 聂荣县| 博兴县| 杨浦区| 出国| 双流县| 舟山市| 如皋市| 和政县| 闸北区| 泽普县| 望奎县| 岚皋县| 平顶山市| 微博| 巴彦淖尔市| 普洱| 桑植县| 什邡市| 军事| 博客|