<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Keyur Somaiya on Medium]]></title>
        <description><![CDATA[Stories by Keyur Somaiya on Medium]]></description>
        <link>https://medium.com/@keyur.somaiya?source=rss-cd154c83f924------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*crQR2b-N1u0rNmuV4SpSHg.jpeg</url>
            <title>Stories by Keyur Somaiya on Medium</title>
            <link>https://medium.com/@keyur.somaiya?source=rss-cd154c83f924------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 05:09:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@keyur.somaiya/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[gRPC and .NET Core: Building Robust and Fast Microservice APIs]]></title>
            <link>https://medium.com/simform-engineering/grpc-and-net-core-building-robust-and-fast-microservice-apis-9aded797c6a8?source=rss-cd154c83f924------2</link>
            <guid isPermaLink="false">https://medium.com/p/9aded797c6a8</guid>
            <category><![CDATA[net-core-6]]></category>
            <category><![CDATA[grpc-client]]></category>
            <category><![CDATA[net8]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[grpc]]></category>
            <dc:creator><![CDATA[Keyur Somaiya]]></dc:creator>
            <pubDate>Mon, 23 Dec 2024 05:57:25 GMT</pubDate>
            <atom:updated>2024-12-23T05:57:25.711Z</atom:updated>
            <content:encoded><![CDATA[<h3>gRPC and .NET Core: Building Robust and Fast Microservice APIs</h3><p><em>Take your microservices to the next level with gRPC and .NET Core</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wD1B1pmR4BSroxhWUC4dYQ.png" /></figure><p><em>If you’re here, you’re probably interested in gRPC and how it can make communication between services faster and more efficient. Stick with me, and by the end of this guide, you’ll know exactly what gRPC is and why it’s so powerful. Let’s get started!</em></p><h3>What is gRPC?</h3><p>gRPC stands for <em>Google Remote Procedure Calls</em>, a high-performance, open-source framework developed by <strong>Google</strong>.</p><p>It enables efficient communication between services in and across data centers. It uses<strong> HTTP/2</strong> for transport and <strong>Protocol Buffers</strong> as the interface description language, and it also offers various features like authentication, load balancing, and more.</p><h4><strong>Key Benefits of gRPC</strong></h4><ul><li><strong>High Performance</strong>: Uses HTTP/2 features like multiplexing and header compression.</li><li><strong>Language Agnostic:</strong> Compatible with multiple programming languages.</li><li><strong>Strongly Typed:</strong> Uses Protocol Buffers for clear and efficient interface definitions.</li><li><strong>Streaming Support: </strong>Enables client, server, and bidirectional streaming for real-time communication.</li><li><strong>Tooling: </strong>Excellent support in .NET, with code generation and Visual Studio integration.</li></ul><h4>Protocol Buffers: The Backbone of gRPC</h4><p>Communication in gRPC revolves around Protocol Buffers, which act as a contract between the client and server. A .proto file defines service methods and message types for requests and responses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5FgUXzHGdsbUpj2RgiijnQ.png" /><figcaption>Protofile</figcaption></figure><p>The .proto file is the blueprint for gRPC communication. It compiles into code for your chosen language (e.g., C# in .NET), generating classes for seamless client-server interaction. Servers implement these methods, while clients use generated stubs to invoke them.</p><p>Protobuf ensures compact, efficient messaging, supports schema evolution, and works across multiple languages, making it integral to gRPC.</p><h4>Why Combine gRPC with .NET?</h4><p>.NET (formerly .NET Core) is a high-performance, cross-platform framework for modern, cloud-based applications. Pairing it with gRPC allows developers to build fast, scalable, and reliable APIs using a cutting-edge technology stack.</p><p>You might wonder, “If REST can do the same, why use gRPC?” <br>Let’s compare:</p><h4>gRPC vs. REST: Key Differences</h4><ul><li><strong>Protocol</strong>: gRPC uses HTTP/2; REST typically relies on HTTP/1.1.</li><li><strong>Data Format:</strong> gRPC employs Protobuf (binary), while REST often uses JSON (text).</li><li><strong>Performance:</strong> gRPC is faster due to binary serialization and HTTP/2 optimizations.</li><li><strong>Contract:</strong> gRPC has strongly typed contracts; REST APIs are more loosely defined.</li><li><strong>Streaming:</strong> gRPC supports client, server, and bidirectional streaming natively, unlike REST.</li></ul><p>Let’s dive into a hands-on project to implement gRPC with .NET Core. In this exercise, we’ll develop two distinct services: a client and a server. Our objective is to create a simple gRPC service for managing product data. The client will request product details, add new products, and interact seamlessly with the server to receive the appropriate responses.</p><h3>Setting Up the Development Environment</h3><p>Let’s move on to setting up the development environment for our gRPC project.</p><p>This initial setup will provide a hands-on introduction to creating, managing, and communicating between gRPC services. By the end of this section, you will have a functioning client-server application that demonstrates basic gRPC interactions, such as product retrieval and addition.</p><p>Before we start, make sure you have the following installed:</p><ul><li><strong>.NET SDK:</strong> Download and install the .NET SDK from the <a href="https://dotnet.microsoft.com/download">official .NET website</a>.</li><li><strong>IDE:</strong> You can use Visual Studio, Visual Studio Code, or any other code editor. Visual Studio and Visual Studio Code are commonly used.</li></ul><h4><strong>1. Creating the gRPC Service Project</strong></h4><p>Once your development environment is ready, creating the gRPC service is next. For this guide, we will set up a new gRPC service project. Here’s how you can do it:</p><ul><li>Open Visual Studio (or your IDE).</li><li>Go to <strong>File &gt; New &gt; Project</strong> and select <strong>gRPC Service</strong>.</li><li>Click <strong>Next</strong> and name the project (e.g., <em>GrpcServer</em>).</li><li>You can use an existing solution or create a new one. Here, we’ll create a new solution named GrpcService.</li><li>Select the framework (e.g., .NET Core, .NET 6/7).</li><li>Click <strong>Create</strong> to generate the project.</li></ul><h4><strong>2. Creating a gRPC Client in the Same Solution</strong></h4><p>If you plan to create a client within the same solution, follow these steps to set up a new console application that will interact with your gRPC service:</p><p><strong>Add a Client Project</strong>:</p><ul><li>Right-click the solution (<em>GrpcService</em>) &gt; <strong>Add &gt; New Project</strong>.</li><li>Select <strong>Console App</strong>, name it (e.g., <em>GrpcClient</em>), and click <strong>Create</strong>.</li></ul><p><strong>Install NuGet Packages</strong>: To enable the client project to make gRPC calls, we need to add the required NuGet packages, so let’s add it</p><ul><li>Right-click <em>GrpcClient</em> &gt; <strong>Manage NuGet Packages</strong>.</li><li>Install the following packages</li><li>Grpc.Net.Client</li><li>Google.Protobuf</li><li>Grpc.Tools</li></ul><h4><strong>3. Creating the </strong><strong>.proto File for the Product Service</strong></h4><ul><li>Define product.protoin <em>GrpcServer:<br></em>Add this content to product.proto</li></ul><pre>syntax = &quot;proto3&quot;;<br><br>option csharp_namespace = &quot;GrpcServer.Protos&quot;;<br>package product;<br><br>import &quot;google/protobuf/empty.proto&quot;; // Import Empty<br><br>service Product {<br>  rpc GetProduct(ProductRequest) returns (ProductResponse); // Fetch a product by ID.<br>  rpc AddProduct(ProductRequest) returns (ProductResponse); // Add a new product.<br>  rpc ListProducts(google.protobuf.Empty) returns (stream ProductResponse); // Stream all products.<br>}<br><br>message ProductRequest {<br>  int32 ProductId = 1;<br>  string ProductName = 2;<br>  string ProductDescription = 3;<br>  double ProductPrice = 4;<br>}<br><br>message ProductResponse {<br>  int32 ProductId = 1;<br>  string ProductName = 2;<br>  string ProductDescription = 3;<br>  double ProductPrice = 4;<br>}</pre><p><strong>Service Methods and their Overview</strong>:</p><ul><li>GetProduct: Retrieves a product by its ID.</li><li>AddProduct: Adds a new product.</li><li>ListProducts: Streams a list of all products.</li><li>ProductRequest: Input data for a product (ID, name, description, price).</li><li>ProductResponse: Output data for a product (same structure).</li></ul><p><strong>Set Up Build Action</strong>:<br>Right-click product.proto &gt; <strong>Properties</strong> &gt; Set <strong>Build Action</strong> to Protobuf.</p><p><strong>Generate C# Code</strong>:<br>Ensure the .proto file is referenced in the .csproj file for the <em>GrpcServer</em> project to generate the necessary C# code.</p><h4><strong>4. Implement the gRPC Service Logic</strong></h4><p>With product.proto defined, the next step is to implement the ProductService class. This class will handle the core logic for product operations like retrieving, adding, and listing products. Each method will process incoming requests, perform the necessary operations (e.g., interact with a data source), and return responses.</p><p><strong>Create the </strong><strong>ProductItem Model</strong>:<br>To manage product data within the service, create a simple model class called ProductItem. This will represent individual products with properties such as ID, name, description, and price.</p><p><strong>Steps to Create the Model</strong>:</p><ul><li>Add a new folder named <strong>Models</strong> to the project.</li><li>Inside the <strong>Models</strong> folder, create a class file named <strong>ProductItem.cs</strong> and define the class as follows:</li></ul><pre> public class ProductItem<br> {<br>     public int ProductId { get; set; }<br>     public string ProductName { get; set; }<br>     public string ProductDescription { get; set; }<br>     public double ProductPrice { get; set; }<br> }</pre><p>Inside the <strong>GrpcService &gt; Services</strong> folder, add a new class named <strong>ProductService</strong> and include the following code:</p><pre>public class ProductService : Product.ProductBase<br>{<br><br>    private static readonly List&lt;ProductItem&gt; Products = new List&lt;ProductItem&gt;<br>    {<br>        new ProductItem { ProductId = 1, ProductName = &quot;Product 1&quot;, ProductDescription = &quot;Description for Product 1&quot;, ProductPrice = 150.00 },<br>        new ProductItem { ProductId = 2, ProductName = &quot;Product 2&quot;, ProductDescription = &quot;Description for Product 2&quot;, ProductPrice = 250.00 },<br>        new ProductItem { ProductId = 3, ProductName = &quot;Product 3&quot;, ProductDescription = &quot;Description for Product 3&quot;, ProductPrice = 350.00 },<br>    };<br><br>    public override Task&lt;ProductResponse&gt; GetProduct(ProductRequest request, ServerCallContext context)<br>    {<br>       <br>        var product = Products.FirstOrDefault(p =&gt; p.ProductId == request.ProductId);<br><br>        if (product == null)<br>        {<br>            throw new RpcException(new Status(StatusCode.NotFound, $&quot;Product with ID {request.ProductId} not found&quot;));<br>        }<br><br>        var response = new ProductResponse<br>        {<br>            ProductId = product.ProductId,<br>            ProductName = product.ProductName,<br>            ProductDescription = product.ProductDescription,<br>            ProductPrice = product.ProductPrice<br>        };<br><br>        return Task.FromResult(response);<br>    }<br>    public override Task&lt;ProductResponse&gt; AddProduct(ProductRequest request, ServerCallContext context)<br>    {<br>        var newProduct = new ProductItem<br>        {<br>            ProductId = Products.Count + 1,<br>            ProductName = request.ProductName,<br>            ProductDescription = request.ProductDescription,<br>            ProductPrice = request.ProductPrice<br>        };<br><br>        Products.Add(newProduct);<br><br>        var response = new ProductResponse<br>        {<br>            ProductId = newProduct.ProductId,<br>            ProductName = newProduct.ProductName,<br>            ProductDescription = newProduct.ProductDescription,<br>            ProductPrice = newProduct.ProductPrice<br>        };<br><br>        return Task.FromResult(response);<br>    }<br>    public override async Task ListProducts(Empty request, IServerStreamWriter&lt;ProductResponse&gt; responseStream, ServerCallContext context)<br>    {<br>        foreach (var product in Products)<br>        {<br>            var response = new ProductResponse<br>            {<br>                ProductId = product.ProductId,<br>                ProductName = product.ProductName,<br>                ProductDescription = product.ProductDescription,<br>                ProductPrice = product.ProductPrice<br>            };<br><br>            await responseStream.WriteAsync(response);<br>        }<br>    }<br>}</pre><h4>5. <strong>Register the ProductService in </strong><strong>Program.cs</strong></h4><ul><li>Open the Program.cs file in your <strong>GrpcServer</strong> project.</li><li>Add the following line to map the ProductService to the gRPC middleware:</li></ul><pre>app.MapGrpcService&lt;ProductService&gt;();</pre><h4><strong>6. Setup Grpc Client project</strong></h4><p>Now that the <strong>GrpcServer</strong> project is complete, let’s move on to implementing the <strong>GrpcClient</strong> to interact with the server.</p><p>Before writing the client logic, we need to define the communication contract using the same .proto file. Follow these steps:</p><p><strong>Create a Protos Folder</strong>:</p><ul><li>In the <strong>GrpcClient</strong> project, right-click on the project in <strong>Solution Explorer</strong>.</li><li>Select <strong>Add &gt; New Folder</strong> and name it <strong>Protos</strong>.</li></ul><p><strong>Add the </strong><strong>product.proto File</strong>:</p><ul><li>Right-click the <strong>Protos</strong> folder and choose <strong>Add &gt; New Item</strong>.</li><li>Select <strong>Text File</strong>, name it, and save it inside the <strong>Protos</strong> folder.</li><li>Copy the product.proto file content from the <strong>GrpcServer</strong> project (where you defined the service).</li></ul><p><strong>Configure the Client Project to Use the </strong><strong>product.proto File</strong>:</p><ul><li>Open the <strong>client project (.csproj)</strong> file.</li><li>Add the following &lt;ItemGroup&gt; element to include the product.proto file and set the GrpcServices to <strong>Client</strong></li></ul><pre>&lt;ItemGroup&gt;<br>  &lt;Protobuf Include=&quot;Protos\product.proto&quot; GrpcServices=&quot;Client&quot; /&gt;<br>&lt;/ItemGroup&gt;</pre><p>This ensures that the product.proto file is included in the build process and the necessary client-side gRPC code is generated.</p><h4><strong>7. Modify the </strong><strong>Program.cs File in the Client Project</strong>:</h4><p>First, open the <strong>launchSettings.json</strong> file in the GrpcClientproject and copy the applicationUrl. This is the URL the client will use to connect to the server.</p><p>Now, update the <strong>Program.cs</strong> file in the project <strong>GrpcClient </strong>to load the server address from the configuration and use it when creating the GrpcChannel:</p><p>Here’s the updated <strong>Program.cs</strong> code for the <strong>GrpcClient</strong>:</p><pre>public class Program<br>{<br>    private static GrpcChannel channel; <br><br>    public static async Task Main(string[] args)<br>    {<br>        bool exit = false;<br><br>        // Initialize the channel once at the start<br>        channel = GrpcChannel.ForAddress(&quot;http://localhost:5056&quot;);<br><br>        while (!exit)<br>        {<br>            Console.WriteLine(&quot;\nSelect an option:&quot;);<br>            Console.WriteLine(&quot;1 - Add Product&quot;);<br>            Console.WriteLine(&quot;2 - Get Product&quot;);<br>            Console.WriteLine(&quot;3 - List Products&quot;);<br>            Console.WriteLine(&quot;4 - Run all demos&quot;);<br>            Console.WriteLine(&quot;0 - Exit&quot;);<br>            Console.Write(&quot;Enter your choice: &quot;);<br><br>            var choice = Console.ReadLine();<br><br>            switch (choice)<br>            {<br>                case &quot;1&quot;:<br>                    await AddProduct();<br>                    break;<br>                case &quot;2&quot;:<br>                    await GetProduct();<br>                    break;<br>                case &quot;3&quot;:<br>                    await ListProducts();<br>                    break;<br>                case &quot;4&quot;:<br>                    await AddProduct();<br>                    await GetProduct();<br>                    await ListProducts();<br>                    break;<br>                case &quot;0&quot;:<br>                    exit = true;<br>                    break;<br>                default:<br>                    Console.WriteLine(&quot;Invalid choice. Please try again.&quot;);<br>                    break;<br>            }<br>        }<br><br>        // Shutdown the channel when the program exits<br>        await channel.ShutdownAsync();<br><br>        Console.WriteLine(&quot;Press any key to exit...&quot;);<br>        Console.ReadKey();<br>    }<br><br>    private static async Task GetProduct()<br>    {<br>        var client = new Product.ProductClient(channel);<br><br>        for (int i = 1; i &lt;= 3; i++)<br>        {<br>            var productRequest = new ProductRequest { ProductId = i };<br>            var productResponse = await client.GetProductAsync(productRequest);<br><br>            Console.WriteLine($&quot;Request ProductId: {i}&quot;);<br>            Console.WriteLine($&quot;Product Name: {productResponse.ProductName}&quot;);<br>            Console.WriteLine($&quot;Product Description: {productResponse.ProductDescription}&quot;);<br>            Console.WriteLine($&quot;Product Price: {productResponse.ProductPrice}&quot;);<br>            Console.WriteLine(&quot;---------------------------------------------------&quot;);<br>        }<br>    }<br><br>    private static async Task AddProduct()<br>    {<br>        var client = new Product.ProductClient(channel);<br><br>        var newProductRequest = new ProductRequest<br>        {<br>            ProductName = &quot;New Product&quot;,<br>            ProductDescription = &quot;A demo product&quot;,<br>            ProductPrice = 499.99<br>        };<br><br>        var response = await client.AddProductAsync(newProductRequest);<br>        Console.WriteLine($&quot;Added Product - ID: {response.ProductId}, Name: {response.ProductName}&quot;);<br>    }<br><br>    private static async Task ListProducts()<br>    {<br>        var client = new Product.ProductClient(channel);<br><br>        using var call = client.ListProducts(new Empty());<br><br>        await foreach (var product in call.ResponseStream.ReadAllAsync())<br>        {<br>            Console.WriteLine($&quot;Product - ID: {product.ProductId}, Name: {product.ProductName}&quot;);<br>        }<br>    }<br>}</pre><p>Don&#39;t forget to replace applicationUrlwith your channel address.</p><h4>8. Time to Test Changes</h4><p>Now that we’ve implemented the necessary changes, it’s time to test them. Follow these steps to ensure everything is functioning as expected:</p><p><strong>Set Up Multiple Startup Projects:</strong></p><ol><li>Right-click the solution in <strong>Solution Explorer</strong> and select <strong>Properties</strong>.</li><li>Under <strong>Startup Project</strong>, select <strong>Multiple Startup Projects</strong>.</li><li>Set <strong>Action</strong> to <strong>Start</strong> for both GrpcClient and GrpcServer.</li><li>Click <strong>OK</strong>.</li></ol><p><strong>Run the Application:</strong></p><ol><li>Click <strong>Start</strong> (F5) to launch both GrpcServer and GrpcClient.</li><li>The GrpcClient the console will show options like</li></ol><p><strong>Select an Option</strong>:</p><ul><li>Choose any of the available options to execute a gRPC call. For example, you can select <strong>Add Product </strong>or <strong>Get Product</strong>.</li><li>Once you make a selection, you’ll see the result displayed in the console.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*tl2qirxUu3fn0mBh-vpRhQ.png" /><figcaption>GrpcClientOutput</figcaption></figure><p>Through this journey, we successfully demonstrated how the GrpcClient communicates with the GrpcService using gRPC, showcasing the fundamentals of client-server interaction and verifying responses in action.</p><p>This brings us to the end of our introduction to gRPC. I hope you found this session insightful and enjoyable. If you have any questions or need further clarification, please share them in the comments below.</p><p>For a hands-on reference, you can explore the Git repository <a href="https://github.com/keyur-s-simformsolutions/GrpcService">here</a>.</p><blockquote><strong>For more updates on the latest tools and technologies, follow the </strong><a href="https://medium.com/simform-engineering"><strong>Simform Engineering</strong></a><strong> blog.</strong></blockquote><blockquote><strong>Follow Us: </strong><a href="https://twitter.com/simform"><strong>Twitter</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/simform/"><strong>LinkedIn</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9aded797c6a8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/simform-engineering/grpc-and-net-core-building-robust-and-fast-microservice-apis-9aded797c6a8">gRPC and .NET Core: Building Robust and Fast Microservice APIs</a> was originally published in <a href="https://medium.com/simform-engineering">Simform Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>