Skip to content

Instantly share code, notes, and snippets.

@jonasfj
Created January 23, 2019 09:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonasfj/4d1dd980994cd923e045af79fe2fab4c to your computer and use it in GitHub Desktop.
Save jonasfj/4d1dd980994cd923e045af79fe2fab4c to your computer and use it in GitHub Desktop.
Example of how to generate GRPC APIs from protobufs and use them in Dart.
// Copyright 2019 Google LLC.
// SPDX-License-Identifier: Apache-2.0
//
// Experiments with dart, grpc and googleapis
// ==========================================
//
// 1. Install `protoc`
// 2. `pub global activate protoc_plugin`
// 3. `git clone https://github.com/googleapis/googleapis`
// 4. `protoc --dart_out=grpc:lib/src/generated -I googleapis/ -I /usr/local/include/ googleapis/google/cloud/vision/v1/image_annotator.proto`
//
import 'package:dart_grpc_googleapis/src/generated/google/cloud/vision/v1/image_annotator.pb.dart';
import 'package:dart_grpc_googleapis/src/generated/google/cloud/vision/v1/image_annotator.pbgrpc.dart';
import 'package:path/path.dart';
import 'package:grpc/grpc.dart';
import 'dart:io';
// Assuming image.jpg and credentials.json are next the current file.
var _imageFile = join(dirname(Platform.script.path), 'image.jpg');
var _serviceAccountFile =
join(dirname(Platform.script.path), 'credentials.json');
void main() async {
// Find the service end-point in .proto files or reference documentation.
final serviceName = "vision.googleapis.com";
final port = 443;
// Setup a channel
var channel = ClientChannel(serviceName,
port: port,
options: ChannelOptions(
credentials: ChannelCredentials.secure(),
));
// Authenticate using credentials
var auth = JwtServiceAccountAuthenticator(
await File(_serviceAccountFile).readAsString());
var client = ImageAnnotatorClient(channel, options: auth.toCallOptions);
// Use the generated API clients
var res = await client.batchAnnotateImages(BatchAnnotateImagesRequest()
..requests.add(AnnotateImageRequest()
..image = (Image()..content = await File(_imageFile).readAsBytes())
..features.add(Feature()..type = Feature_Type.LABEL_DETECTION)));
for (var label in res.responses[0].labelAnnotations) {
print(label.description);
}
// Close the channel
await channel.shutdown();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment