- 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.