Reader small image

You're reading from  Modern API Development with Spring 6 and Spring Boot 3 - Second Edition

Product typeBook
Published inSep 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781804613276
Edition2nd Edition
Languages
Concepts
Right arrow
Author (1)
Sourabh Sharma
Sourabh Sharma
author image
Sourabh Sharma

Sourabh Sharma is a Senior Development Manager at Oracle with over 20 years of experience in the industry. He is a manager and architect who has been designing on-premise and cloud-based applications using Java, Javascript, and Oracle DB. Sourabh has worked with leading companies and delivered enterprise products and applications. His expertise lies in conceptualizing, modeling, designing, and developing N-tier and cloud-based web applications while leading teams. Sourabh's experience also includes developing microservice-based solutions and implementing various types of workflow and orchestration engines. He believes in continuous learning and sharing knowledge through his books and training.
Read more about Sourabh Sharma

Right arrow

gRPC API Development and Testing

You will learn how to implement gRPC-based APIs in this chapter. You will learn how to write the gRPC server and client along with writing APIs based on gRPC. In the later part of this chapter, you will be introduced to microservices and see how they can help you to design modern, scalable architecture.

You will also go through the implementation of two services – the gRPC server and the gRPC client. gRPC-based APIs are more popular and preferred over REST APIs for service-to-service communication in a microservice-based system. Hence, gRPC development skills are important in the API space.

After completing this chapter, you will be well versed in the gRPC server and client development, gRPC-based API testing automation, and microservice concepts.

You will explore the following topics in this chapter:

  • Writing an API
  • Developing the gRPC server
  • Handling errors
  • Developing the gRPC client
  • Learning microservice concepts...

Technical requirements

This chapter contains a great deal of theory on gRPC. However, you will also undertake the development and testing of gRPC-based web services, for which you will need the following:

  • Any Java IDE, such as NetBeans, IntelliJ, or Eclipse
  • Java Development Kit (JDK) 17
  • An internet connection to clone the code and download the dependencies and Gradle
  • Postman/cURL (for API testing)

Please visit the following link to check the code: https://github.com/PacktPublishing/Modern-API-Development-with-Spring-6-and-Spring-Boot-3/tree/dev/Chapter11

So, let’s begin!

Writing an API

In this section, we will write the API using Protocol Buffer (Protobuf) for a payment service. If you recall, this is the piece that you haven’t yet implemented in the sample e-commerce app.

Before writing the API, let’s set up the Gradle project.

Setting up the project

The code for this chapter will contain three projects under the Chapter11 directory – the API, server, and client:

  • API: This is a library project that contains the .proto file and its generated Java classes packaged in a JAR file. This project will generate the payment-gateway-api-0.0.1.jar library artifact, which you will publish in a local repository. This library will then be used in both the server and client projects.
  • Server: This project represents the gRPC server, which will implement the gRPC services and serve the gRPC requests.
  • Client: This project contains the gRPC client, which will call the gRPC server. To kick off the inter-service communication...

Developing the gRPC server

You need to configure the server project before implementing these abstract classes. Let’s configure the server project first.

The server project directory structure will look like the following. The project root directory contains the build.gradle and settings.gradle files:

├── server    ├── build.gradle
    ├── gradle
    │   └── wrapper
    ├── gradlew
    ├── gradlew.bat
    ├── settings.gradle
    └── src
        ├── main
        │   ├── java
     ...

Coding for handling errors

You may have already gone through the theory-based Handling errors and error status codes section in Chapter 10, Getting Started with gRPC, where google.rpc.Status and gRPC status codes were discussed. You may want to revisit that section before going through this section as here you are going to write the actual code.

io.grpc.ServerInterceptor is a thread-safe interface for intercepting incoming calls that can be used for cross-cutting calls, such as authentication and authorization, logging, and monitoring. Let’s use it to write ExceptionInterceptor, as shown in the following code block:

@Componentpublic class ExceptionInterceptor implements ServerInterceptor {
 @Override
 public <RQT, RST> ServerCall.Listener<RQT> interceptCall(
    ServerCall<RQT, RST> serverCall, Metadata
        metadata,
    ServerCallHandler<RQT, RST> serverCallHandler...

Developing the gRPC client

A client project’s directory structure will look as follows. The project root directory contains the build.gradle and settings.gradle files, as shown in the following directory tree structure:

├── client   ├── build.gradle
   ├── gradle
   │   └── wrapper
   ├── gradlew
   ├── gradlew.bat
   ├── settings.gradle
   └── src
       ├── main
       │   ├── java
       │   │   └── com
       │...

Understanding microservice concepts

Microservices are self-contained lightweight processes that communicate over a network. Microservices provide narrowly focused APIs to their consumers. These APIs can be implemented using REST, gRPC, or events.

Microservices are not new—they have been around for many years. For example, Stubby, a general-purpose infrastructure based on RPC, was used in Google data centers in the early 2000s to connect several services with and across data centers.

They have seen a recent rise in popularity and visibility. Before microservices became popular, monolithic architectures were mainly used for developing on-premises and cloud-based applications.

A monolithic architecture allows the development of different components, such as presentation, application logic, business logic, and data access objects (DAOs), and then you either bundle them together in an enterprise archive (EAR) or web archive (WAR) or store them in a single directory hierarchy...

Summary

In this chapter, you explored Protobuf and gRPC-based service implementation. You developed the gRPC server and then consumed its services by developing a gRPC client. You learned about unit-testing the gRPC server and handling exceptions for gRPC-based services, and you also learned about the basic concepts of microservices.

You now have the skills to develop gRPC-based services (servers) and clients by defining the services using Protobuf.

In the next chapter, you will learn about distributed logging and tracing in web services.

Questions

  1. Why should you use gRPC for binary large object transfers via HTTP/2?
  2. You have implemented exception handling using com.google.rpc.Status. Can you do so without using this?
  3. What is the difference between com.google.rpc.Status and io.grpc.Status?

Answers

  1. Because, unlike HTTP libraries, gRPC libraries also provide the following features:
    • Interaction with flow control at the application layer
    • Cascading call cancellation
    • Load balancing and failover
  2. Yes, you can. You can use the metadata shown in the following code block. However, making use of com.google.rpc.Status allows you to use the details (with a type of Any) object, which can capture more information:
    Metadata.Key<SourceId.Response> key = ProtoUtils    .keyForProto(SourceId.Response. getDefaultInstance);Metadata metadata = new Metadata();metadata.put(key, sourceIdResponse);respObserver.onError(Status.INVALID_ARGUMENT   .withDescription("Invalid Source ID")   .asRuntimeException(metadata));
  3. com.google.rpc.Status can include details of the Any type, which can be used to provide more error details. io.grpc.Status does not have a field that contains the error details. You must rely on another class’...
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Modern API Development with Spring 6 and Spring Boot 3 - Second Edition
Published in: Sep 2023Publisher: PacktISBN-13: 9781804613276
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 €14.99/month. Cancel anytime

Author (1)

author image
Sourabh Sharma

Sourabh Sharma is a Senior Development Manager at Oracle with over 20 years of experience in the industry. He is a manager and architect who has been designing on-premise and cloud-based applications using Java, Javascript, and Oracle DB. Sourabh has worked with leading companies and delivered enterprise products and applications. His expertise lies in conceptualizing, modeling, designing, and developing N-tier and cloud-based web applications while leading teams. Sourabh's experience also includes developing microservice-based solutions and implementing various types of workflow and orchestration engines. He believes in continuous learning and sharing knowledge through his books and training.
Read more about Sourabh Sharma