Skip to main content

Protocol Buffers

You're reading Integrator 5.0.0. The newest release is 5.1.0. Go to the newest release

Protocol Buffers (protobuf) support is built into the gRPC module. The ballerina/protobuf module (v1.8.0) provides the runtime types for pre-defined protobuf types including Any, Duration, Timestamp, Struct, Empty, and scalar wrappers. Use the bal grpc CLI to generate Ballerina code from .proto files.

Module​

ballerina/protobuf (used via ballerina/grpc)

Usage​

Generate code from .proto files​

# Generate Ballerina client/service stubs from a .proto file
bal grpc --input order_service.proto --output generated

Use generated gRPC client​

import ballerina/grpc;

// Generated from .proto files using bal grpc CLI
OrderServiceClient client = check new ("http://localhost:9090");
Order order = check client->GetOrder({order_id: "ORD-001"});

Work with protobuf Any type​

import ballerina/protobuf.types.'any;

type Product record {|
string name;
decimal price;
|};

// Pack a value into Any
Product product = {name: "Widget", price: 9.99};
'any:Any packed = check 'any:pack(product);

// Unpack from Any
Product unpacked = check 'any:unpack(packed);

Protobuf timestamps and durations​

import ballerina/time;

// Protobuf timestamps map to time:Utc
time:Utc timestamp = time:utcNow();

// Protobuf durations map to time:Seconds
time:Seconds duration = 3600.5d;

Submodules​

SubmoduleProto typeBallerina mappingDescription
protobuf.types.'anygoogle.protobuf.AnyAny recordContainer for arbitrary typed values with pack/unpack functions.
protobuf.types.durationgoogle.protobuf.Durationtime:SecondsSigned duration with nanosecond precision.
protobuf.types.emptygoogle.protobuf.EmptyEmpty recordEmpty message (no fields).
protobuf.types.structgoogle.protobuf.Structmap<anydata>Dynamic key-value structure.
protobuf.types.timestampgoogle.protobuf.Timestamptime:UtcPoint in time with nanosecond precision.
protobuf.types.wrappersgoogle.protobuf.*Valueint, float, string, boolean, byte[]Nullable scalar wrappers for optional primitives.

Functions​

FunctionSignatureDescription
packpack(ValueType message) returns Any|ErrorPack a Ballerina value into a protobuf Any.
unpackunpack(Any anyValue, ValueTypeDesc targetTypeOfAny = <>) returns targetTypeOfAny|ErrorUnpack a protobuf Any into a typed Ballerina value.

Supported value types​

The pack and unpack functions support:

int, float, string, boolean, time:Utc, time:Seconds, record {}, (), byte[], map<anydata>

Was this page helpful?