Protocol Buffer is an ecosystem to define the structure of your data. This helps you define your contract between clients. It is developed by Google
Let us understand this with an example.
Wherever you create any application then you create a service or microservices. You expose multiple APIs on the service and define a fixed Request and Response contract for your APIs. Protocol Buffer helps you to define the Request and Response Contract. This is one such example where a Protocol Buffer is being used.
Once you define the structure of the data the Protocol Buffer provides the mechanism to serialize the data.
What is data Serialization and why is it needed in Protocol Buffers?
As Protocol Buffer helps you to define the contract. Once the contract is finalized then you will create an object of that contract and pass that object to some service for processing.
For example, you created an API to create an employee so you will define a contract for employee registration. Let us say the contract needed is
- name
- phone_number
- address
- age
You will create an object of this employee contract and pass that object to the registration API. In the software world, you can’t pass the object directly, you first need to convert that object into a series of bytes that save the object state and make it transmittable form. This process of converting the object into a series of bytes is called serialization.
We create a contract from Protocol Buffer and then create an object from those contracts such that it can be transmitted over the wire to multiple services so serialization is needed in Protocol Buffer.
Protocol Buffer is language-neutral
You define the contract once using Protocol Buffer in a .proto file.
Then you can generate language language-specific codebase from the .proto file using the proto compiler.
You just need to run the proto compiler to generate your code base in any programming language like Java, C++, NodeJS, etc, and use the generated code for defining contracts in your specified language.
You can use it as a single proto file for all the languages so it is language-neutral
Protocol Buffer is Fast and compact as compared to JSON
JSON is also used to define the contract but the Protocol Buffer is fast and compact
Unlike XML and JSON, which are human-readable, Protocol Buffers use binary format, which is more compact and faster for a computer to read and write.
What is Interface Definition Language
The contract of the Protocol Buffer is defined using a standard language called Interface Definition Language
message Employee {
required string name = 1;
required int32 id = 2;
optional string email = 3;
}
References
Next: Java Hello World Application