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

API Specifications and Implementation

In previous chapters, we learned about the design aspects of REST APIs and the Spring fundamentals required to develop RESTful web services. In this chapter, you’ll make use of these two areas to implement REST APIs.

We have chosen a design-first approach for implementation to make our development process understandable for non-technical stakeholders as well. To make this approach possible, we will make use of the OpenAPI Specification (OAS) to, first, design an API and, later, implement it. We will also learn how to handle errors that occur while serving the request. In this chapter, we will use the example of designing and implementing an API of a sample e-commerce app.

By the end of this chapter, you should be able to design the API specifications and make use of the OpenAPI codegen to generate the code for models and API Java interfaces. You will also know how to write the pseudo-Spring controllers to implement the API Java interfaces...

Technical requirements

You need the following to execute the instructions in this and the following chapters:

  • Any Java IDE, such as NetBeans, IntelliJ, or Eclipse
  • Java Development Kit (JDK) 17
  • An internet connection to download the dependencies and Gradle

You can find the code files for this chapter on GitHub at https://github.com/PacktPublishing/Modern-API-Development-with-Spring-6-and-Spring-Boot-3/tree/main/Chapter03.

Designing APIs with OAS

You can directly start coding the API; however, this approach leads to many issues, such as frequent modifications, difficulty in API management, and difficulty in reviews specifically led by non-technical domain teams. Therefore, you should use the design-first approach.

The first question that comes to mind is, how can we design REST APIs? You learned in Chapter 1, RESTful Web Service Fundamentals, that there is no existing standard to govern REST API implementation. OAS was introduced to solve at least the aspects of the REST API’s specification and description. It allows you to write REST APIs in the YAML Ain’t Markup Language (YAML) or JavaScript Object Notation (JSON) markup languages.

We’ll use version 3.0 of OAS (https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md) to implement the e-commerce app REST API. We’ll use YAML (pronounced as yamel, rhyming with camel), which is cleaner and easier to read...

Understanding the basic structure of OAS

The OpenAPI definition structure can be divided into the following sections (all are keywords and case-sensitive):

  • openapi (version)
  • info
  • externalDocs
  • servers
  • tags
  • paths
  • components

All the preceding terms are part of root. The first three sections (openapi, info, and externalDocs) are used to define the metadata of the API.

You can place an API’s definition either in a single file or divided into multiple files. OAS supports both. We’ll use a single file to define the sample e-commerce API.

Instead of discussing all the sections theoretically and then writing the e-commerce API definitions, we’ll do both together. First, we’ll cover each section definition of the e-commerce API, and then we’ll discuss why we have used it and what it implies.

The metadata sections of OAS

Let’s have a look at the metadata sections of the e-commerce API definitions:

...

Converting OAS to Spring code

I am sure you are as excited as I am to start implementing the API. So far, we have learned about the RESTful web service theory and concepts and Spring fundamentals, and also designed our first API specs for a sample e-commerce application.

For this section, you can either clone the Git repository (https://github.com/PacktPublishing/Modern-API-Development-with-Spring-6-and-Spring-Boot-3) or start to create a Spring project from scratch using Spring Initializr (https://start.spring.io/) with the following options:

  • Project: Gradle - Groovy
  • Language: Java
  • Spring Boot: 3.0.8

Or use the 3.X.X available version. Replace the project metadata with your preferred values

  • Packaging: Jar
  • Java: 17
  • Dependencies: Spring Web

Once you open the project in your favorite IDE (IntelliJ, Eclipse, or NetBeans), you can add the following extra dependencies required for OpenAPI support under dependencies in the build.gradle file...

Implementing the OAS code interfaces

So far, we have generated code that consists of e-commerce app models and API Java interfaces. These generated interfaces contain all the annotations as per the YAML description provided by us. For example, in CartApi.java, @RequestMapping, @PathVariable, and @RequestBody contain the endpoint path (/api/v1/carts/{customerId}/items), the value of the path variable (such as {customerId} in path), and the request payload (such as Item), respectively. Similarly, generated models contain all the mapping required to support the JSON and XML content types.

Swagger Codegen writes the Spring code for us. We just need to implement the interface and write the business logic inside it. Swagger Codegen generates the API Java interfaces for each of the provided tags. For example, it generates the CartApi and PaymentAPI Java interfaces for the cart and payment tags, respectively. All the paths are clubbed together into a single Java interface based on the given...

Adding a Global Exception Handler

We 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 type of exception. This exception handler method will generate user-friendly error messages with other related information.

You can make use of the Project Lombok library if approved by your 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;
  private...

Testing the implementation of the API

Once the code is ready to run, you can compile and build the artifact using the following command from the root folder of the project:

$ ./gradlew clean build

The previous command removes the build folder and generates the artifact (the compiled classes and JAR). After the successful build, you can run the application using the following command:

$ java -jar build/libs/Chapter03-0.0.1-SNAPSHOT.jar

Now, we can perform tests using the curl command:

$ curl --request GET 'http://localhost:8080/api/v1/carts/1' --header 'Accept: application/xml'

This command calls the GET request for /carts with ID 1. Here, we demand the XML response using the Accept header, and we get the following response:

<Error>  <errorCode>PACKT-0001</errorCode>
  <message>The system is unable to complete the request.
           Contact system...

Summary

In this chapter, we opted for the design-first approach to writing RESTful web services. You learned how to write an API description using OAS and how to generate models and API Java interfaces using the Swagger Codegen tool (using the Gradle plugin). We also implemented a Global Exception Handler to centralize the handling of all the exceptions. Once you have the API Java interfaces, you can write their implementations for business logic. Now, you know how to use OAS and Swagger Codegen to write RESTful APIs. You also now know how to handle exceptions globally.

In the next chapter, we’ll implement fully fledged API Java interfaces with business logic with database persistence.

Questions

  1. What is OpenAPI and how does it help?
  2. How can you define a nested array in a model in a YAML OAS-based file?
  3. What annotations do we need to implement a Global Exception Handler?
  4. How can you use models or classes written in Java code in your OpenAPI description?
  5. Why do we only generate models and API Java interfaces using Swagger Codegen?

Answers

  1. OAS was introduced to solve at least a few aspects of a REST API’s specification and description. It allows you to write REST APIs in the YAML or JSON markup languages, which allows you to interact with all stakeholders, including those who are non-technical, for review and discussion in the development phase. It also allows you to generate documentation, models, interfaces, clients, and servers in different languages.
  2. The array is defined using the following code:
    type: arrayitems:  type: array  items:    type: string
  3. You need a class annotation, @ControllerAdvice, and a method annotation, @ExceptionHandler, to implement the Global Exception Handler.
  4. You can use --type-mappings and --import-mappings rawOptions in the swaggerSources task of the build.gradle file.
  5. We only generate the models and API Java interfaces using Swagger Codegen because this allows the complete implementation of controllers by developers...

Further reading

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