Reader small image

You're reading from  Web API Development with ASP.NET Core 8

Product typeBook
Published inApr 2024
PublisherPackt
ISBN-139781804610954
Edition1st Edition
Concepts
Right arrow
Author (1)
Xiaodi Yan
Xiaodi Yan
author image
Xiaodi Yan

Xiaodi Yan is a seasoned software engineer with a proven track record in the IT industry. Since 2015, he has been awarded Microsoft MVP, showcasing his dedication to and expertise in .NET, AI, DevOps, and cloud computing. He is also a Microsoft Certified Trainer (MCT), Azure Solutions Architect Expert, and LinkedIn Learning instructor. Xiaodi often presents at conferences and user groups, leveraging his extensive experience to engage and inspire audiences. Based in Wellington, New Zealand, he spearheads the Wellington .NET User Group, fostering a vibrant community of like-minded professionals. Connect with Xiaodi on LinkedIn to stay updated on his latest insights.
Read more about Xiaodi Yan

Right arrow

Getting Started with gRPC

Besides RESTful APIs, there are other types of APIs. One of them is the remote procedure call (RPC)-based API, which we introduced in Chapter 1. gRPC is a high-performance RPC framework developed by Google. Now, it is an open-source project under the Cloud Native Computing Foundation (CNCF), and it is becoming more and more popular.

ASP.NET Core provides a set of gRPC tools to help us build gRPC services. In this chapter, we will introduce the fundamentals of gRPC and Protocol Buffers (Protobuf) messages. First, we will learn how to define protobuf messages and gRPC services. Then, we will learn how to implement gRPC services in ASP.NET Core, empowering us to communicate seamlessly between different applications. We will be covering the following topics in this chapter:

  • Recap of gRPC
  • Setting up a gRPC project
  • Defining gRPC services and messages
  • Implementing gRPC services and clients
  • Consuming gRPC services in ASP.NET Core applications...

Technical requirements

The code examples in this chapter can be found at https://github.com/PacktPublishing/Web-API-Development-with-ASP.NET-Core-8/tree/main/samples/chapter11. You can use VS 2022 or VS Code to open the solutions.

Recap of gRPC

If you have read Chapter 1, you should be familiar with the concept of RPC – it is a protocol that allows a program to call a procedure on a remote machine. Unlike RESTful APIs, which center around resources, RPC-based APIs focus on actions. So, RPC methods support various types of actions besides CRUD operations.

gRPC is one of the most popular RPC frameworks. It provides many benefits over traditional RPC frameworks. As we mentioned in Chapter 1, gRPC is based on HTTP/2, which is more efficient than HTTP/1.1. gRPC uses protobuf as the default data serialization format, which is a binary format that is more compact and efficient than JSON. The tooling support for gRPC is also very good. It follows the contract-first approach, which means we can create language-neutral service definitions and generate code for different languages. It also supports streaming, which is a very useful feature for real-time communication.

With the increasing popularity of microservices...

Setting up a gRPC project

In this section, we will build a gRPC project using the dotnet CLI. We will also create a client project to consume the gRPC service. We will be using the same project throughout this chapter.

Creating a new gRPC project

To create a new gRPC project, we can use the dotnet new command. The dotnet CLI provides a template for gRPC projects, which includes a basic gRPC service. We can use the following command to create a new gRPC project:

dotnet new grpc -o GrpcDemo

The -o option specifies the output directory. After running the command, we will see that a project named GrpcDemo is created.

If you prefer to use VS 2022, you can also create a new gRPC project in VS 2022 using the built-in gRPC template. You can select the ASP.NET Core gRPC Service template when creating a new project, as shown in Figure 11.1:

Figure 11.1 – Creating a new gRPC project in VS 2022

Figure 11.1 – Creating a new gRPC project in VS 2022

After creating the project, you can use VS Code or...

Creating protobuf messages

In this section, we will learn how to create protobuf messages. We will introduce the concepts of protobuf messages and how to define them in a proto file.

gRPC is a contract-first framework, meaning that the gRPC service and messages must be defined in a proto file. When we talk about messages, we are talking about the data that is sent between the client and the server. While gRPC messages may be similar to the data model in RESTful APIs, they are not the same. RESTful APIs are centered around resources, and the data model is usually a resource model that can be mapped to one or multiple database tables. In contrast, gRPC is action-based, and the message can be any other type of data model or other message sent between the client and the server. Therefore, gRPC messages may not be exactly mapped to a resource model in RESTful APIs.

For example, when creating an invoice through a RESTful API using JSON as the data format, we need to send an HTTP POST...

Creating a protobuf service

Now that we have understood the definition of a protobuf message, we can move on to defining protobuf services. These services are comprised of RPC methods, each of which has a request and response message. To facilitate the implementation of these services, gRPC tooling will generate the necessary C# code, which can then be used as the base class for the service.

gRPC supports four types of RPC methods:

  • Unary RPC: The client sends a single request message to the server and receives a single response message in return. This type of method is suitable for applications that need single request-response exchanges.
  • Server streaming RPC: The client sends a single request message to the server and the server then responds with a stream of response messages. This type of method allows for continuous data exchange between the client and server.
  • Client streaming RPC: The client sends a stream request message to the server and the server then responds...

Consuming gRPC services in ASP.NET Core applications

In the previous section, we learned how to create console applications to consume gRPC services. In this section, we will integrate gRPC services into ASP.NET Core applications. We will reuse the gRPC services we created in the previous section, and we will create a new ASP.NET Core application to consume the gRPC services.

To get started with the steps outlined in this section, begin with the GrpcDemo-v3 folder of the source code. The complete code for this section can be found in the GrpcDemo-v4 folder.

In the console applications, we used the GrpcChannel class to create a gRPC channel, after which we used the gRPC channel to create a gRPC client, as shown in the following code:

using var channel = GrpcChannel.ForAddress("https://localhost:7179");var client = new Contact.ContactClient(channel);

In ASP.NET Core applications, a better way to create a gRPC client is to use the IHttpClientFactory interface with...

Updating proto files

gRPC is a contract-first RPC framework. This means that the server and the client communicate with each other using a contract, which is defined in a proto file. Inevitably, the contract will change over time. In this section, we will learn how to update the contract and how to handle the changes in the server and the client.

Once a proto file is used in production, we need to consider backward compatibility when we update the proto file. This is because the existing clients may use the old version of the proto file, which may not be compatible with the new version of the proto file. If the new version of the contract is not backward compatible, the existing clients will break.

The following changes are backward compatible:

  • Adding new fields to a request message: If the client does not send the new fields, the server can use the default values of the new fields.
  • Adding new fields to a response message: If the response message contains the new...

Summary

In this chapter, we explored the fundamentals of gRPC services and clients. We discussed the field types that are used in protobuf, including the scalar types and some other types such as DateTime, enum, repeated fields, and map fields. Then, we learned about four types of gRPC services: unary, server streaming, client streaming, and bidirectional streaming. We explored how to implement each type of gRPC service and how to create a gRPC client to consume the gRPC service. Additionally, we demonstrated how to use the AddGrpcClient() method to register a gRPC client in the DI container of an ASP.NET Core application and how to use the gRPC client to consume a unary gRPC service. Finally, we discussed how to update the proto files and how to handle the changes in the server and the client.

To simplify the code samples, we did not use any database access code in the gRPC services. In a real-world application, we may need to interact with a database or other external services...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Web API Development with ASP.NET Core 8
Published in: Apr 2024Publisher: PacktISBN-13: 9781804610954
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Xiaodi Yan

Xiaodi Yan is a seasoned software engineer with a proven track record in the IT industry. Since 2015, he has been awarded Microsoft MVP, showcasing his dedication to and expertise in .NET, AI, DevOps, and cloud computing. He is also a Microsoft Certified Trainer (MCT), Azure Solutions Architect Expert, and LinkedIn Learning instructor. Xiaodi often presents at conferences and user groups, leveraging his extensive experience to engage and inspire audiences. Based in Wellington, New Zealand, he spearheads the Wellington .NET User Group, fostering a vibrant community of like-minded professionals. Connect with Xiaodi on LinkedIn to stay updated on his latest insights.
Read more about Xiaodi Yan