40 releases

0.13.1 May 5, 2025
0.13.0 Mar 25, 2025
0.12.3 Sep 26, 2024
0.12.1 Jul 17, 2024
0.1.0-alpha.6 Nov 10, 2019

#43 in Network programming

Download history 830319/week @ 2025-02-01 1012277/week @ 2025-02-08 1129051/week @ 2025-02-15 1164190/week @ 2025-02-22 1466826/week @ 2025-03-01 1440080/week @ 2025-03-08 1575661/week @ 2025-03-15 1918447/week @ 2025-03-22 1278497/week @ 2025-03-29 1383509/week @ 2025-04-05 1179198/week @ 2025-04-12 1163277/week @ 2025-04-19 1030548/week @ 2025-04-26 1158277/week @ 2025-05-03 1197443/week @ 2025-05-10 1019689/week @ 2025-05-17

4,604,095 downloads per month
Used in 1,344 crates (663 directly)

MIT license

98KB
2K SLoC

tonic-build

Compiles proto files via prost and generates service stubs and proto definitions for use with tonic.

Features

Required dependencies

[dependencies]
tonic = "<tonic-version>"
prost = "<prost-version>"

[build-dependencies]
tonic-build = "<tonic-version>"

Examples

Simple

In build.rs:

fn main() -> Result<(), Box<dyn std::error::Error>> {
    tonic_build::compile_protos("proto/service.proto")?;
    Ok(())
}

Configuration

fn main() -> Result<(), Box<dyn std::error::Error>> {
   tonic_build::configure()
        .build_server(false)
        .compile_protos(
            &["proto/helloworld/helloworld.proto"],
            &["proto/helloworld"],
        )?;
   Ok(())
}

See more examples here

Google APIs example

A good way to use Google API is probably using git submodules.

So suppose in our proto folder we do:

git submodule add https://github.com/googleapis/googleapis

git submodule update --remote

And a bunch of Google proto files in structure will be like this:

├── googleapis
│   └── google
│       ├── api
│       │   ├── annotations.proto
│       │   ├── client.proto
│       │   ├── field_behavior.proto
│       │   ├── http.proto
│       │   └── resource.proto
│       └── pubsub
│           └── v1
│               ├── pubsub.proto
│               └── schema.proto

Then we can generate Rust code via this setup in our build.rs

fn main() {
    tonic_build::configure()
        .build_server(false)
        //.out_dir("src/google")  // you can change the generated code's location
        .compile_protos(
            &["proto/googleapis/google/pubsub/v1/pubsub.proto"],
            &["proto/googleapis"], // specify the root location to search proto dependencies
        ).unwrap();
}

Then you can reference the generated Rust like this this in your code:

pub mod api {
    tonic::include_proto!("google.pubsub.v1");
}
use api::{publisher_client::PublisherClient, ListTopicsRequest};

Or if you want to save the generated code in your own code base, you can uncomment the line .out_dir(...) above, and in your lib file config a mod like this:

pub mod google {
    #[path = ""]
    pub mod pubsub {
        #[path = "google.pubsub.v1.rs"]
        pub mod v1;
    }
}

See the example here

Dependencies

~0.5–11MB
~132K SLoC