Book Image

Modern API Development with Spring and Spring Boot

By : Sourabh Sharma
Book Image

Modern API Development with Spring and Spring Boot

By: Sourabh Sharma

Overview of this book

The philosophy of API development has evolved over the years to serve the modern needs of enterprise architecture, and developers need to know how to adapt to these modern API design principles. Apps are now developed with APIs that enable ease of integration for the cloud environment and distributed systems. With this Spring book, you'll discover various kinds of production-ready API implementation using REST APIs and explore async using the reactive paradigm, gRPC, and GraphQL. You'll learn how to design evolving REST-based APIs supported by HATEOAS and ETAGs and develop reactive, async, non-blocking APIs. After that, you'll see how to secure REST APIs using Spring Security and find out how the APIs that you develop are consumed by the app's UI. The book then takes you through the process of testing, deploying, logging, and monitoring your APIs. You'll also explore API development using gRPC and GraphQL and design modern scalable architecture with microservices. The book helps you gain practical knowledge of modern API implementation using a sample e-commerce app. By the end of this Spring book, you'll be able to develop, test, and deploy highly scalable, maintainable, and developer-friendly APIs to help your customers to transform their business.
Table of Contents (21 chapters)
1
Section 1: RESTful Web Services
7
Section 2: Security, UI, Testing, and Deployment
12
Section 3: gRPC, Logging, and Monitoring
16
Section 4: GraphQL

Adding a Global Exception Handler

We'll have multiple controllers that consist of multiple methods. Each method may have checked exceptions or throw runtime exceptions. We should have a centralized place to handle all these errors for better maintainability and modularity and clean code.

Spring provides an AOP feature for this. We just need to write a single class annotated with @ControllerAdvice. Then, we just need to add @ExceptionHandler for each of the exceptions. This exception handler method will generate user-friendly error messages with other related information.

You can make use of the Lombok library if approved by your respective organization for third-party library usage. This will remove the verbosity of the code for getters, setters, constructors, and so on.

Let's first write the Error class in the exceptions package that contains all the error information:

public class Error {
  private static final long serialVersionUID = 1L;
  ...