Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Protocol Buffers Handbook
Protocol Buffers Handbook

Protocol Buffers Handbook: Getting deeper into Protobuf internals and its usage

Arrow left icon
Profile Icon Clément Jean
Arrow right icon
zł39.99 zł129.99
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (2 Ratings)
eBook Apr 2024 226 pages 1st Edition
eBook
zł39.99 zł129.99
Paperback
zł161.99
Subscription
Free Trial
Arrow left icon
Profile Icon Clément Jean
Arrow right icon
zł39.99 zł129.99
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (2 Ratings)
eBook Apr 2024 226 pages 1st Edition
eBook
zł39.99 zł129.99
Paperback
zł161.99
Subscription
Free Trial
eBook
zł39.99 zł129.99
Paperback
zł161.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Protocol Buffers Handbook

Protobuf is a Language

It is time to discover the Protobuf language and its syntax. In this chapter, we are going to see all the concepts that we need in order to write Protobuf schemas. This chapter is, thus, designed as a kind of documentation that can be read from start to end but also can be referenced in future chapters. As such, you might not understand every implication of each concept, but that is fine. Be confident, and we will make sure that you get all the knowledge you need throughout this book.

In this chapter, we will learn about the following:

  • Top-level statements
  • User-defined types
  • Out-of-the-box types
  • Services

At the end of this chapter, you will know all the most common concepts in the Protobuf language. You will understand what they are used for, and you will be able to start writing proto files.

Technical requirements

All the code examples that you will see in this section can be found under the directory called chapter2 in the GitHub repository (https://github.com/PacktPublishing/Protocol-Buffers-Handbook).

In the following sections, I will be using some extended Backus-Naur form (EBNF) notation (https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form) to describe the syntax of all the elements. The following elements will be used:

|   alternation (or)
()  grouping
[]  option (zero or one time)
{}  repetition (any number of times)

Do not worry too much, though. I am only writing in the EBNF for people who are interested and to emphasize that Protobuf is a language. If you feel like this is too overwhelming, you can just skip this part and look at the examples I will be providing.

On top of that, I will be omitting details for simplicity. However, all the details are available in the official specifications:

...

Top-level statements

In this section, we will see all the top-level statements in the order they should appear in a proto file according to the Protobuf Style Guide (https://protobuf.dev/programming-guides/style/). We are going to go through their meaning, and we are going to see some simple examples.

Syntax

The syntax statement is one of the easiest statements to understand. This tells the compiler (protoc) the version we are using in the file and, therefore, the features we can and cannot access:

EBNF – Syntax statement

version = "proto2" | "proto3" | "editions"
syntax = "syntax" "=" ("'" version "'" | '"' version '"') ";"

As you can see, there are three versions that we can pass to the syntax statement:

  • proto2
  • proto3
  • editions

Now, all of this is a little bit obscure, and these names, especially proto2 and proto3, are...

User-defined types

enum

You are certainly already familiar with enums in your favorite language, and they are pretty much the same in Protobuf. When we know all the possible values of a type, we use enums to create a lightweight representation of each value:

EBNF – Enum syntax

enumValueOption = optionName "=" constant
enumField = ident "=" [ "-" ] intLit [ "[" enumValueOption { ","  enumValueOption } "]" ]";"
enumBody = "{" { option | enumField | reserved } "}"
enum = "enum" ident enumBody

As such, an enum in Protobuf looks like the following:

enum PhoneType {
  PHONE_TYPE_MOBILE = 0;
  PHONE_TYPE_HOME = 1;
  //...
}

You can see that we are adding the name of the enum (in UPPER_SNAKE_CASE) as the prefix of each value, and then we have this magic number following the equal sign. The naming is purely done according to convention...

Message

Messages are the most complex concept in Protobuf. This is why we are going to split this section into multiple subsections. We will talk about these concepts in the following order:

  • Options: They are repeated in all the following concepts
  • Field, reserved, map, and oneof: These concepts are all about defining fields and specifying some serialization behavior
  • Nested messages

EBNF – Message syntax

messageBody = "{" { field | enum | message | option | oneof | mapField | reserved } "}"
message = "message" ident messageBody

Option

Since we are already familiar with options at this point, we can skip them. However, I still want to mention all the types that you can look for in the descriptor.proto (check https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/descriptor.proto) file so that you can check all the possible options available. Here is the list per concept:

message -> MessageOptions...

Services

Finally, the last concept we are going to see is service. service is designed for Protobuf interaction with RPC frameworks, such as gRPC. They define a type-safe contract that the server should implement and that the client can call:

EBNF – Service syntax

rpc = "rpc" ident "(" [ "stream" ] messageType ")" "returns" "(" [ "stream" ] messageType ")" (( "{" option "}" ) | ";")
service = "service" ident "{" { option | rpc } "}"

For example, we could have the following service:

service BookService {
  rpc ListBooks(ListBooksRequest) returns (ListBooksResponse);
  rpc GetBook(GetBookRequest) returns (Book);
  rpc CreateBook(CreateBookRequest) returns (Book);
  rpc UpdateBook(UpdateBookRequest) returns (Book);
  rpc DeleteBook(DeleteBookRequest) returns (google.protobuf.Empty...

Out-of-the-box types

On top of all the scalar types that Protobuf provides as part of the language, it also provides some already-defined types called well-known types (WKTs). All these types can be found in the src/google/protobuf folder in the GitHub repository (https://github.com/protocolbuffers/protobuf/tree/main/src/google/protobuf), and they are all defined under the google.protobuf package.

Here is a list of the most common WKTs available:

  • Duration
  • Timestamp
  • FieldMask
  • Any
  • Struct

Let’s go through all of these types and see what they are used for.

Duration and timestamp

These two types are pretty interesting because they show us the importance of naming, documenting with comments, and separating definitions into different files for reusability. In fact, these two types have the same definitions except for the message name. Here are the diff command results between those two (simplified):

-message Timestamp {
-  // Represents...

Summary

We have come a long way. This chapter was intense, and there are probably things that you are still not entirely sure about. That is normal; do not worry. You can refer to it later if you have questions about a certain Protobuf concept.

In this chapter, we saw how to write top-level statements such as Edition, Syntax, Import, Package, and Options. We then saw how to write enums and messages to create type definitions. After that, we saw what the services are. Finally, we talked about the well-known types that are provided out of the box when you use Protobuf.

In the next chapter, we will talk about the Protobuf text format and how we can set values to fields in a nonprogrammatic way.

Quiz

  1. Where can you find the proto files for the well-known types?
    1. Nowhere; this is hidden inside the Protobuf language.
    2. Nowhere; we need to define them ourselves.
    3. On the GitHub repository under the src/google/protobuf folder.
  2. Where can you find the message definitions for the option types?
    1. On the GitHub repository under the folder src/google/protobuf in the file called descriptor.proto.
    2. Nowhere; this is hidden inside the Protobuf language.
    3. Nowhere; we need to define them ourselves.
  3. Why do we define an UNSPECIFIED value in enums for proto3?
    1. In proto3, enums are closed, so we do not need to.
    2. In proto3, enums are open, and UNSPECIFIED is used as the default value.
    3. It is not needed in proto3, only in proto2.
  4. When do we need nesting types inside a message?
    1. When we want to specialize a type with fully qualified names.
    2. When a type is only relevant in the parent context.
    3. All the above.

Answers

  1. C
  2. A
  3. B
  4. C
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Encode and decode complex data structures, enhancing data interchange efficiency across systems
  • Understand Protobuf by mastering the syntax, schema evolution, customizations, and more
  • Integrate Protobuf into your preferred language ecosystem, ensuring interoperability and effective collaboration
  • Purchase of the print or Kindle book includes a free PDF eBook

Description

Explore how Protocol Buffers (Protobuf) serialize structured data and provides a language-neutral, platform-neutral, and extensible solution. With this guide to mastering Protobuf, you'll build your skills to effectively serialize, transmit, and manage data across diverse platforms and languages. This book will help you enter the world of Protocol Buffers by unraveling the intricate nuances of Protobuf syntax and showing you how to define complex data structures. As you progress, you’ll learn schema evolution, ensuring seamless compatibility as your projects evolve. The book also covers advanced topics such as custom options and plugins, allowing you to tailor validation processes to your specific requirements. You’ll understand how to automate project builds using cutting-edge tools such as Buf and Bazel, streamlining your development workflow. With hands-on projects in Go and Python programming, you’ll learn how to practically apply Protobuf concepts. Later chapters will show you how to integrate data interchange capabilities across different programming languages, enabling efficient collaboration and system interoperability. By the end of this book, you’ll have a solid understanding of Protobuf internals, enabling you to discern when and how to use and redefine your approach to data serialization.

Who is this book for?

This book is for software developers, from novices to experienced programmers, who are interested in harnessing the power of Protocol Buffers. It's particularly valuable for those seeking efficient data serialization solutions for APIs, microservices, and data-intensive applications. The content covered in this book accommodates diverse programming backgrounds, offering essential knowledge to both beginners and seasoned developers.

What you will learn

  • Focus on efficient data interchange with advanced serialization techniques
  • Master Protocol Buffers syntax and schema evolution
  • Perform custom validation via Protoc plugins for precise data integrity
  • Integrate languages seamlessly for versatile system development
  • Automate project building with Buf and Bazel
  • Get to grips with Go and Python integration for real-world Protobuf applications
  • Streamline collaboration through system interoperability with Protobuf

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 30, 2024
Length: 226 pages
Edition : 1st
Language : English
ISBN-13 : 9781805127215
Category :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Apr 30, 2024
Length: 226 pages
Edition : 1st
Language : English
ISBN-13 : 9781805127215
Category :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just zł20 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just zł20 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 585.97
Mastering Go
zł221.99
Asynchronous Programming in Rust
zł201.99
Protocol Buffers Handbook
zł161.99
Total 585.97 Stars icon
Banner background image

Table of Contents

12 Chapters
Chapter 1: Serialization Primer Chevron down icon Chevron up icon
Chapter 2: Protobuf is a Language Chevron down icon Chevron up icon
Chapter 3: Describing Data with Protobuf Text Format Chevron down icon Chevron up icon
Chapter 4: The Protobuf Compiler Chevron down icon Chevron up icon
Chapter 5: Serialization Internals Chevron down icon Chevron up icon
Chapter 6: Schema Evolution over Time Chevron down icon Chevron up icon
Chapter 7: Implementing the Address Book in Go Chevron down icon Chevron up icon
Chapter 8: Implementing the Address Book in Python Chevron down icon Chevron up icon
Chapter 9: Developing a Protoc Plugin in Golang Chevron down icon Chevron up icon
Chapter 10: Advanced Build Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(2 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Frequent buyer Jun 12, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is an excellent resource for anyone looking to dive deep into the world of Protocol Buffers, whether you’re a beginner or have some prior knowledge.Author does a fantastic job of breaking down the basics and gradually building up to more advanced topics. The examples are practical and relevant, making it easy to see how Protocol Buffers can be applied in real-world scenarios.I particularly appreciated the section on best practices and optimization techniques.The insights provided have already helped me improve the performance of my own projects.Overall, “Protocol Buffers: The Definitive Guide” is well-structured, informative, and engaging. It has definitely earned a permanent spot on my bookshelf.
Amazon Verified review Amazon
Juan Cruz Viotti Jun 26, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I have experience with binary serialisation from a research point of view (University of Oxford) and have worked with binary serialisation formats including Protocol Buffers in the context of IoT, and this book still managed to teach me a bunch of things I didn't know.First of all, Chapter 5 on serialisation internals is a gem. I really wish this book was there by the time I published some of my papers back in the day. I would have cited this book instead of attempting to write quite a lot about these things myself. Furthermore, the book teaches a very nice workflow for introducing readers on how to debug binary payloads, which people otherwise end up learning the hard way.Other than that, this book has a great introduction on writing your own "protoc" plugin/extensions (which I didn't even know was possible), and on using Protocol Buffers with more modern platforms like Buf.If you are into binary serialisation, schemas, or just need to learn Protocol Buffers to get something done, this well-written and pretty concise and to-the-point book might be all you need.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.