{"id":13741418,"url":"https://github.com/ballerina-platform/module-ballerina-grpc","last_synced_at":"2026-01-12T08:04:57.268Z","repository":{"id":36951373,"uuid":"288615146","full_name":"ballerina-platform/module-ballerina-grpc","owner":"ballerina-platform","description":"Ballerina gRPC Module","archived":false,"fork":false,"pushed_at":"2025-04-23T08:55:55.000Z","size":10033,"stargazers_count":123,"open_issues_count":0,"forks_count":46,"subscribers_count":69,"default_branch":"master","last_synced_at":"2025-06-09T05:46:03.354Z","etag":null,"topics":["ballerina","grpc","hacktoberfest","integration","protobuf","wso2"],"latest_commit_sha":null,"homepage":"","language":"Ballerina","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ballerina-platform.png","metadata":{"files":{"readme":"README.md","changelog":"changelog.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2020-08-19T02:37:43.000Z","updated_at":"2025-04-23T08:56:00.000Z","dependencies_parsed_at":"2024-02-16T22:28:30.396Z","dependency_job_id":"45f6292f-b5a7-43ff-b65f-dd7b2fa4276d","html_url":"https://github.com/ballerina-platform/module-ballerina-grpc","commit_stats":null,"previous_names":[],"tags_count":77,"template":false,"template_full_name":null,"purl":"pkg:github/ballerina-platform/module-ballerina-grpc","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ballerina-platform%2Fmodule-ballerina-grpc","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ballerina-platform%2Fmodule-ballerina-grpc/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ballerina-platform%2Fmodule-ballerina-grpc/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ballerina-platform%2Fmodule-ballerina-grpc/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ballerina-platform","download_url":"https://codeload.github.com/ballerina-platform/module-ballerina-grpc/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ballerina-platform%2Fmodule-ballerina-grpc/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":260690958,"owners_count":23047106,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ballerina","grpc","hacktoberfest","integration","protobuf","wso2"],"created_at":"2024-08-03T04:00:59.000Z","updated_at":"2026-01-12T08:04:57.263Z","avatar_url":"https://github.com/ballerina-platform.png","language":"Ballerina","funding_links":[],"categories":["Language-Specific"],"sub_categories":["Ballerina"],"readme":"Ballerina gRPC Library\n===================\n\n  [![Build](https://github.com/ballerina-platform/module-ballerina-grpc/actions/workflows/build-timestamped-master.yml/badge.svg)](https://github.com/ballerina-platform/module-ballerina-grpc/actions/workflows/build-timestamped-master.yml)\n  [![codecov](https://codecov.io/gh/ballerina-platform/module-ballerina-grpc/branch/master/graph/badge.svg)](https://codecov.io/gh/ballerina-platform/module-ballerina-grpc)\n  [![Trivy](https://github.com/ballerina-platform/module-ballerina-grpc/actions/workflows/trivy-scan.yml/badge.svg)](https://github.com/ballerina-platform/module-ballerina-grpc/actions/workflows/trivy-scan.yml)\n  [![GraalVM Check](https://github.com/ballerina-platform/module-ballerina-grpc/actions/workflows/build-with-bal-test-graalvm.yml/badge.svg)](https://github.com/ballerina-platform/module-ballerina-grpc/actions/workflows/build-with-bal-test-graalvm.yml)\n  [![GitHub Last Commit](https://img.shields.io/github/last-commit/ballerina-platform/module-ballerina-grpc.svg)](https://github.com/ballerina-platform/module-ballerina-grpc/commits/master)\n  [![Github issues](https://img.shields.io/github/issues/ballerina-platform/ballerina-standard-library/module/grpc.svg?label=Open%20Issues)](https://github.com/ballerina-platform/ballerina-standard-library/labels/module%2Fgrpc)\n\nThis library provides APIs for connecting and interacting with gRPC endpoints.\n\ngRPC is an inter-process communication technology that allows you to connect, invoke, and operate distributed, heterogeneous applications as easily as making a local function call. The gRPC protocol is layered over HTTP/2 and uses Protocol Buffers for marshaling/unmarshaling messages. This makes gRPC highly efficient on wire and a simple service definition framework.\n\nWhen you develop a gRPC application, the first thing you do is define a service definition using Protocol Buffers.\n\n### Protocol buffers\nThis is a mechanism to serialize the structured data introduced by Google and used by the gRPC framework. Defining the service using Protocol Buffers includes defining remote methods in the service and defining message types that are sent across the network. A sample service definition is shown below.\n\n```proto\nsyntax = \"proto3\";\n\nservice Helloworld {\n    rpc hello(HelloRequest) returns (HelloResponse);\n}\n\nmessage HelloRequest {\n    string name = 1;\n}\n\nmessage HelloResponse {\n    string message = 1;\n}\n```\n\ngRPC allows client applications to directly call the server-side methods using the auto-generated stubs. Protocol\nBuffer compiler is used to generate the stubs for the specified language. In Ballerina, the stubs are generated using the built-in 'Protocol Buffers to Ballerina' tool.\n\nFor information on how to generate Ballerina code for Protocol Buffers definition, see [Write a gRPC service with Ballerina](https://ballerina.io/learn/write-a-grpc-service-with-ballerina/).\n\n### gRPC communication patterns\nThe common communication pattern between a client and server is simple request-response style communication. However, with gRPC, you can leverage different inter-process communication patterns other than the simple request-response pattern.\nThis library supports four fundamental communication patterns used in gRPC-based applications: simple RPC(unary RPC), server streaming RPC, client streaming RPC, and bidirectional streaming RPC.\n\n#### Simple RPC (Unary RPC)\nIn this pattern, the client invokes a remote function of a server and sends a single request to the server. The server sends a single response in return to the client along with status details.\n\n```proto\nservice HelloWorld {\n    rpc hello (google.protobuf.StringValue)\n          returns (google.protobuf.StringValue);\n}\n```\n##### Implement the gRPC server\nThe code snippet given below contains a service that sends a response to each request.\n\n```ballerina\n// The gRPC service is attached to the listener.\nservice HelloWorld on new grpc:Listener(9090)  {\n    // The function accepts a string message.\n    remote function hello(string name) returns string|error {\n        // Send the response to the client.\n        return \"Hi \" + name + \"! Greetings from gRPC service!\");\n    }\n}\n```\n##### Implement the gRPC client\nThe code snippet given below calls the above service in a synchronized manner using an auto-generated Ballerina stub.\n\n```ballerina\n// Use ‘HelloWorldClient’ to execute the call in the synchronized mode.\nHelloWorldClient helloClient = check new(\"http://localhost:9090\");\n\n// Call the service remote function using a client stub.\nstring responseFromServer = check helloClient-\u003ehello(\"Ballerina\");\n```\n\n#### Server streaming RPC\nIn server-side streaming RPC, the server sends back a sequence of responses after getting the client's request message. After sending all the server responses, the server marks the end of the stream by sending the server status details.\nYou can invoke this in a non-blocking manner.\n\n```proto\nservice HelloWorld {\n    rpc lotsOfReplies (google.protobuf.StringValue)\n          returns (stream google.protobuf.StringValue);\n}\n```\n##### Implement the gRPC server\nThe code snippet given below contains a service that sends a sequence of responses to each request.\n\n```ballerina\n// The gRPC service is attached to the listener.\nservice HelloWorld on new grpc:Listener(9090) {\n    remote function lotsOfReplies(string name) returns stream\u003cstring, grpc:Error?\u003e {\n        string[] greets = [\"Hi \" + name, \"Welcome \" + name];\n        // Send multiple responses to the client.\n        return greets.toStream();\n   }\n}\n```\n\n##### Implement the gRPC server\nThe code snippet given below calls the above service using the auto-generated Ballerina client stub and reads multiple server responses using a stream.\nHere, the message stream is ended with a `()` value.\n\n```ballerina\n   // Client endpoint configurations.\n    HelloWorldClient helloworldClient = check new(\"http://localhost:9090\");\n\n    // Execute the service streaming call by registering a message listener.\n    stream\u003cstring, grpc:Error?\u003e result = \n                                check helloworldClient-\u003elotsOfReplies(\"Ballerina\");\n```\n\n#### Client streaming RPC\nIn client streaming RPC, the client sends multiple messages to the server instead of a single request. The server sends back a single response to the client.\n\n```proto\nservice HelloWorld {\n    rpc lotsOfGreetings (stream google.protobuf.StringValue)\n          returns (google.protobuf.StringValue);\n}\n```\n\n##### Implement the gRPC server\nThe code snippet given below contains a service that receives a sequence of requests from the client and sends a single response in return.\n\n```ballerina\n// The gRPC service is attached to the listener.\nservice HelloWorld on new grpc:Listener(9090) {\n\n    // This function is triggered when a new client connection is initialized.\n    remote function lotsOfGreetings(stream\u003cstring, grpc:Error?\u003e clientStream) \n                                                        returns string|error {\n        // Iterate through the client stream\n        check clientStream.forEach(function(string name) {\n            // Handle the message sent from the stream here\n        });\n        // A nil value is returned once the client stream is ended\n        // Return server response to the client.\n        return \"Ack\";\n    }\n}\n```\n\n##### Implement the gRPC server\nThe code snippet given below calls the above service using the auto-generated Ballerina client stub and sends multiple request messages from the server.\n\n```ballerina\n    // Client endpoint configurations.\n    HelloWorldClient helloworldClient = check new(\"http://localhost:9090\");\n\n    // Execute the service streaming call by registering a message listener.\n    LotsOfGreetingsStreamingClient streamingClient = \n                                        check helloworldClient-\u003elotsOfGreetings();\n\n    // Send multiple messages to the server.\n    string[] greets = [\"Hi\", \"Hey\", \"GM\"];\n    foreach string greet in greets {\n        grpc:Error? connErr = streamingClient-\u003esendstring(greet + \" \" + \"Ballerina\");\n    }\n\n    // Once all the messages are sent, the client notifies the server \n    // by closing the stream.\n    grpc:Error? result = streamingClient-\u003ecomplete();\n    // Receive the message from the server.\n    string|grpc:Error response = streamingClient-\u003ereceiveString();\n...\n```\n\n#### Bidirectional streaming RPC\nIn bidirectional streaming RPC, the client is sending a request to the server as a stream of messages. The server also responds with a stream of messages.\n\n```proto\nservice Chat {\n    rpc chat (stream ChatMessage)\n          returns (stream google.protobuf.StringValue);\n}\n```\n##### Implement the gRPC server\nThe code snippet given below includes a service that handles bidirectional streaming.\n\n```ballerina\n// The gRPC service is attached to the listener.\nservice Chat on new grpc:Listener(9090) {\n\n    //This `resource` is triggered when a new caller connection is initialized.\n    remote function chat(ChatStringCaller caller, \n                                    stream\u003cChatMessage, grpc:Error?\u003e clientStream) {\n        //Iterate through the client stream\n        check clientStream.forEach(function(ChatMessage chatMsg) {\n            // Handle the streamed messages sent from the client here\n            grpc:Error? err = caller-\u003esendString(\n                                    string `${chatMsg.name}: ${chatMsg.message}`);\n        });\n        // A nil value is returned once the client stream is ended\n        // Handle once the client has completed streaming\n        caller-\u003ecomplete();\n    }\n}\n```\n##### Implement the gRPC server\nThe code snippet given below calls the above service using the auto-generated Ballerina client stub and sends multiple request messages to the server and receives multiple responses from the server.\n\n```ballerina\n    // Client endpoint configurations.\n    ChatClient chatClient = check new(\"http://localhost:9090\");\n\n    // Execute the service streaming call by registering a message listener.\n    ChatStreamingClient streamingClient = check chatClient-\u003echat();\n\n    // Send multiple messages to the server.\n    string[] greets = [\"Hi\", \"Hey\", \"GM\"];\n    foreach string greet in greets {\n        ChatMessage mes = {name: \"Ballerina\", message: greet};\n        grpc:Error? connErr = streamingClient-\u003esendChatMessage(mes);\n    }\n\n    // Once all the messages are sent, the server notifies the caller \n    // with a `complete` message.\n    grpc:Error? result = streamingClient-\u003ecomplete();\n    ...\n\n    // Receive the server stream response iteratively.\n    string? result = check streamingClient-\u003ereceiveString();\n    while !(result is ()) {\n        io:println(result);\n        result = streamingClient-\u003ereceiveString();\n    }\n```\n\n### Advanced use cases\n\n#### Use the TLS protocol\n\nThe Ballerina gRPC library allows the use of TLS in communication. This setting expects a secure socket to be\nset in the connection configuration as shown below.\n\n##### Configure TLS in server side\n\n```ballerina\n// Server endpoint configuration with the SSL configurations.\nlistener grpc:Listener ep = new (9090, {\n    host: \"localhost\",\n    secureSocket: {\n        key: {\n            certFile: \"../resource/path/to/public.crt\",\n            keyFile: \"../resource/path/to/private.key\"\n        }\n    }\n});\n\nservice HelloWorld on ep {\n    \n}\n```\n\n##### Configure TLS in client side\n\n```ballerina\n    // Client endpoint configuration with SSL configurations.\n    HelloWorldClient helloWorldClient = check new (\"https://localhost:9090\", {\n        secureSocket: {\n            cert: \"../resource/path/to/public.crt\"\n        }\n    });\n```\n\n#### Use headers\n\nThe Ballerina gRPC library allows to send/receive headers with the request and response using the context record type. The\ncontext record type consists of two fields called headers and content. E.g: For the string message, a type generated context record type will be as follows.\n\n```ballerina\npublic type ContextString record {|\n    string content;\n    map\u003cstring|string[]\u003e headers;\n|};\n```\n\n##### Use headers at the client side\n\n```ballerina\n    // Set the custom headers to the request.\n    ContextString requestMessage =\n    {content: \"WSO2\", headers: {client_header_key: \"0987654321\"}};\n    // Execute the remote call.\n    ContextString result = check ep-\u003ehelloContext(requestMessage);\n    // Read Response content.\n    string content = result.content;\n    // Read Response header value.\n    string headerValue = check grpc:getHeader(result.headers, \n                                                    \"server_header_key\");\n```\n\n##### Use headers at the server side\n\n```ballerina\nservice \"HelloWorld\" on new grpc:Listener(9090) {\n    remote function hello(ContextString request) returns ContextString|error {\n        // Read the request content.\n        string message = \"Hello \" + request.content;\n\n        // Read custom headers in request message.\n        string reqHeader = check grpc:getHeader(request.headers, \n                                                        \"client_header_key\");\n\n        // Send response with custom headers.\n        return {content: message, \n                        headers: {server_header_key: \"Response Header value\"}};\n    }\n}\n```\n\n#### Use deadlines\n\nDeadlines allow gRPC clients to specify how long they are willing to wait for an RPC to complete before the RPC is\nterminated with the `DEADLINE_EXCEEDED` error. In Ballerina, a deadline value is set directly to the headers and it is sent\nvia the request headers.\n\n##### Set a deadline in the request headers\n\n```ballerina\n    time:Utc current = time:utcNow();\n    time:Utc deadline = time:utcAddSeconds(current, 300);\n    map\u003cstring|string[]\u003e headers = grpc:setDeadline(deadline);\n```\n\n##### Check the deadlines\n\n```ballerina\n    boolean cancel = check grpc:isCancelled(request.headers);\n    if (cancel) {\n        return error DeadlineExceededError(\"Deadline exceeded\");\n    }\n```\n\n## Issues and projects\n\nIssues and Projects tabs are disabled for this repository as this is part of the Ballerina Standard Library. To report bugs, request new features, start new discussions, view project boards, etc. please visit Ballerina Standard Library [parent repository](https://github.com/ballerina-platform/ballerina-standard-library). \n\nThis repository only contains the source code for the module.\n\n## Build from the source\n\n### Set Up the prerequisites\n\n* Download and install Java SE Development Kit (JDK) version 21 (from one of the following locations).\n\n   * [Oracle](https://www.oracle.com/java/technologies/downloads/)\n\n   * [OpenJDK](https://adoptium.net/)\n\n        \u003e **Note:** Set the JAVA_HOME environment variable to the path name of the directory into which you installed JDK.\n\n### Build the source\n\nExecute the commands below to build from source.\n\n1. To build the library:\n        \n        ./gradlew clean build\n\n2. To run the integration tests:\n\n        ./gradlew clean test\n\n3. To build the module without the tests:\n\n        ./gradlew clean build -x test\n\n5. To debug the Ballerina implementation against the native implementation:\n   ```\n   ./gradlew clean build -Pdebug=\u003cport\u003e\n   ./gradlew clean test -Pdebug=\u003cport\u003e\n   ```\n\n6. To debug the Ballerina implementation against the Ballerina language:\n   ```\n   ./gradlew clean build -PbalJavaDebug=\u003cport\u003e\n   ./gradlew clean test -PbalJavaDebug=\u003cport\u003e\n   ```\n\n7. Publish the generated artifacts to the local Ballerina central repository:\n    ```\n    ./gradlew clean build -PpublishToLocalCentral=true\n    ```\n8. Publish the generated artifacts to the Ballerina central repository:\n   ```\n   ./gradlew clean build -PpublishToCentral=true\n   ```\n\n## Contribute to Ballerina\n\nAs an open source project, Ballerina welcomes contributions from the community. \n\nFor more information, go to the [contribution guidelines](https://github.com/ballerina-platform/ballerina-lang/blob/master/CONTRIBUTING.md).\n\n## Code of conduct\n\nAll contributors are encouraged to read the [Ballerina Code of Conduct](https://ballerina.io/code-of-conduct).\n\n## Useful links\n\n* Chat live with us via our [Discord server](https://discord.gg/ballerinalang).\n* Post all technical questions on Stack Overflow with the [#ballerina](https://stackoverflow.com/questions/tagged/ballerina) tag.\n* View the [Ballerina performance test results](https://github.com/ballerina-platform/ballerina-lang/blob/master/performance/benchmarks/summary.md).\n* For more information go to [the gRPC Package](https://lib.ballerina.io/ballerina/grpc/latest).\n* For example demonstrations of the usage, go to [Ballerina By Examples](https://ballerina.io/learn/by-example/).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fballerina-platform%2Fmodule-ballerina-grpc","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fballerina-platform%2Fmodule-ballerina-grpc","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fballerina-platform%2Fmodule-ballerina-grpc/lists"}