- Dart:Scalable Application Development
- Davy Mitchell Sergey Akopkokhyants Ivo Balbaert
- 349字
- 2021-07-09 18:56:32
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.
- 計算機網絡
- Android項目開發入門教程
- Learn to Create WordPress Themes by Building 5 Projects
- Arduino by Example
- 騰訊iOS測試實踐
- 程序員面試筆試寶典
- Silverlight魔幻銀燈
- 算法訓練營:提高篇(全彩版)
- 微服務架構深度解析:原理、實踐與進階
- 愛上C語言:C KISS
- 從零開始構建深度前饋神經網絡:Python+TensorFlow 2.x
- ASP.NET Core and Angular 2
- 大話代碼架構:項目實戰版
- Microsoft Windows Identity Foundation Cookbook
- Eclipse開發(學習筆記)