Packages, Imports, and File Organization

Organize protobuf definitions with packages, imports, and file structure conventions. Learn about public imports, package naming, and multi-file project organization.

Advanced Features

Detailed Explanation

Organizing Protobuf Files

As protobuf schemas grow, splitting definitions across files and using packages prevents naming conflicts and improves maintainability. Proper file organization also makes code generation cleaner.

// File: common/v1/types.proto
syntax = "proto3";
package common.v1;

message Pagination {
  int32 page_size = 1;
  string page_token = 2;
}

message PaginationResponse {
  string next_page_token = 1;
  int32 total_count = 2;
}

message Money {
  string currency_code = 1;
  int64 units = 2;
  int32 nanos = 3;
}
// File: product/v1/product.proto
syntax = "proto3";
package product.v1;

import "common/v1/types.proto";

message Product {
  string id = 1;
  string name = 2;
  string description = 3;
  common.v1.Money price = 4;
  repeated string categories = 5;
}

service ProductService {
  rpc GetProduct(GetProductRequest) returns (Product);
  rpc ListProducts(ListProductsRequest) returns (ListProductsResponse);
}

message GetProductRequest {
  string product_id = 1;
}

message ListProductsRequest {
  common.v1.Pagination pagination = 1;
  string category_filter = 2;
}

message ListProductsResponse {
  repeated Product products = 1;
  common.v1.PaginationResponse pagination = 2;
}

Package Naming Conventions

  • Use dot-separated lowercase names matching your organization's namespace
  • Include a version suffix (e.g., product.v1, user.v2)
  • Match the directory structure to the package path: product/v1/product.proto
  • In Go, the package maps to the generated Go package name

Import Types

Import type Syntax Behavior
Standard import "path/to/file.proto"; Types available only in importing file
Public import public "path/to/file.proto"; Types transitively available to importers of this file
Weak import weak "path/to/file.proto"; Non-failing import (rarely used)

File Organization Best Practices

  1. One service per file: Keep service definitions in their own file
  2. Shared types in common/: Place reusable types (Pagination, Money, Address) in a shared package
  3. Version directories: Use v1/, v2/ directories for API versioning
  4. Keep files focused: Each file should define related types; avoid monolithic proto files
  5. Match directory to package: package foo.bar.v1; should be in foo/bar/v1/

Use Case

Structuring protobuf definitions for a microservices architecture with shared types across teams, versioned APIs, and code generation targets for multiple languages.

Try It — Protobuf Definition Parser

Open full tool