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

Writing Business Logic for APIs

You defined API specs using OpenAPI in the previous chapter. API Java interfaces and models were generated by the OpenAPI (Swagger Codegen). In this chapter, you will implement the API’s code in terms of both business logic and data persistence. Here, business logic refers to the actual code you are writing for domain functionalities, which in our case comprise operations performed for e-commerce, such as checking out the shopping cart.

You will write services and repositories for implementation and add hypermedia and entity tags (ETags) to API responses. Hypermedia As The Engine Of Application State (HATEOAS) will be implemented using Spring and Hypertext Application Language (HAL). HAL is one of the standards to implement HATEOAS. Others are Collection+JSON and JSON-LD. You are going to use HAL in this book. You can find a sample of it in the first example in the Adding ETags to API responses section denoted by the "_links" field...

Technical requirements

To execute the instructions in this and the following chapters, you will need any REST API client, such as Insomnia or Postman.

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/Chapter04.

Overview of the service design

We are going to implement a multi-layered architecture that comprises four layers – the presentation layer, application layer, domain layer, and infrastructure layer. Multi-layered architecture is a fundamental building block in the architecture style known as domain-driven design (DDD). Let’s have a brief look at each of these layers:

  • Presentation layer: This layer represents the user interface (UI). In Chapter 7, Designing a User Interface, you’ll develop the UI for a sample e-commerce app.
  • Application layer: The application layer contains the application logic and maintains and coordinates the overall flow of the application. Just to remind you, it only contains the application logic and not the business logic. RESTful web services, async APIs, gRPC APIs, and GraphQL APIs are a part of this layer.

We already covered REST APIs and controllers in Chapter 3, API Specifications and Implementation, which are part...

Adding a Repository component

We’ll use the bottom-to-top approach to add a @Repository component. Let’s start implementing the domain layer with a @Repository component. We’ll implement the service and enhance the @Controller component in subsequent sections accordingly. We will code the @Repository component first, then use it in the @Service component using constructor injection. The @Controller component will be enhanced using the @Service component, which will also be injected into the Controller using constructor injection.

The @Repository annotation

Repository components are Java classes marked with the @Repository annotation. This is a special Spring component that is used for interacting with databases.

@Repository is a general-purpose stereotype that represents both DDD’s Repository and the Java Enterprise Edition (JEE) data access object (DAO) pattern. Developers and teams should handle repository objects based on the underlying approach...

Adding a Service component

The @Service component is an interface that works between controllers and repositories and is where we’ll add the business logic. Though you can directly call repositories from controllers, it is not a good practice as repositories should only be part of the data retrieval and persistence functionalities. Service components also help in sourcing data from various sources, such as databases and other external applications.

Service components are marked with the @Service annotation, which is a specialized Spring @Component that allows implemented classes to be auto-detected using class-path scanning. Service classes are used to add business logic. Like Repository, the Service object also represents both DDD’s Service and JEE’s Business Service Façade patterns. Like Repository, it is also a general-purpose stereotype and can be used according to the underlying approach.

First, we’ll create the service interface, which is...

Implementing hypermedia

We learned about hypermedia and HATEOAS in Chapter 1, RESTful Web Service Fundamentals. Spring provides state-of-the-art support to HATEOAS using the org.springframework.boot: spring-boot-starter-hateoas dependency.

First, we need to make sure that all models returned as part of the API response contain the link field. There are different ways to associate links (that is, the org.springframework.hateoas.Link class) with models, either manually or via auto-generation. Spring HATEOAS’s links and attributes are implemented according to RFC-8288 (https://tools.ietf.org/html/rfc8288). For example, you can create a self-link manually as follows:

import static org.springframework.hateoas.server.mvc. WebMvcLinkBuilder.linkTo;import static org.springframework.hateoas.server.mvc. WebMvcLinkBuilder.methodOn;
// other code blocks…
responseModel.setSelf(linkTo(methodOn(CartController.class)  .getItemsByUserId(userId,item)).withSelfRel())
...

Enhancing the controller with a service and HATEOAS

In Chapter 3, API Specifications and Implementation, we created the Controller class for the Cart API – CartController – which just implements the OpenAPI Codegen-generated API specification interface – CartApi. It was just a mere block of code without any business logic or data persistence calls.

Now, since we have written the repositories, services, and HATEOAS assemblers, we can enhance the API controller class, as shown here:

@RestControllerpublic class CartsController implements CartApi {
  private CartService service;
  private final CartRepresentationModelAssembler assembler;
  public CartsController(CartService service,
     CartRepresentationModelAssembler assembler) {
    this.service = service;
    this.assembler = assembler;
  }

https://github.com/PacktPublishing/Modern-API-Development...

Adding ETags to API responses

An ETag is an HTTP response header that contains a computed hash or equivalent value of the response entity, and a minor change in the entity must change its value. HTTP request objects can then contain the If-None-Match and If-Match headers to receive the conditional responses.

Let’s call an API to retrieve the response with an ETag, as shown next:

$ curl -v --location --request GET 'http://localhost:8080/ api/v1/products/6d62d909-f957-430e-8689-b5129c0bb75e' –-header 'Content-Type: application/json' --header 'Accept: application/json'* … text trimmed
> GET /api/v1/products/6d62d909-f957-430e-8689-b5129c0bb75e HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.55.1
> Content-Type: application/json
> Accept: application/json
>
< HTTP/1.1 200
< ETag: "098e97de3b61db55286f5f2812785116f"
< Content-Type: application/json
< Content-Length: 339
<
{
  ...

Testing the APIs

Now, you must be looking forward to testing. You can find the API client collection at the following location, which is an HTTP Archive file and can be used by Insomnia or Postman API clients. You can import it and then test the APIs:

https://github.com/PacktPublishing/Modern-API-Development-with-Spring-6-and-Spring-Boot-3/blob/main/Chapter04/Chapter04-API-Collection.har

Building and running the Chapter 4 code

You can build the code by running gradlew clean build from the root of the project and run the service using java -jar build/libs/Chapter04-0.0.1-SNAPSHOT.jar. Make sure to use Java 17 in the path.

Summary

In this chapter, we have learned about database migration using Flyway, maintaining and persisting data using repositories, and writing business logic to services. We have also learned how hypermedia can automatically be added to API responses using Spring HATEOAS assemblers. You have now learned about all the RESTful API development practices, which allows you to use this skill in your day-to-day work involving RESTful API development.

So far, we have written synchronous APIs. In the next chapter, you will learn about async APIs and how to implement them using Spring.

Questions

  1. Why is the @Repository class used?
  2. Is it possible to add extra imports or annotations to Swagger-generated classes or models?
  3. How are ETags useful?

Answers

  1. Repository classes are marked with @Repository, which is a specialized @Component that makes these classes auto-detectable by package-level auto-scanning and makes them available for injection. Spring provides these classes especially for DDD repositories and the JEE DAO pattern. This is the layer used by the application for interacting with the database – retrieval and persistence as a central repository.
  2. It is possible to change the way models and APIs are generated. You must copy the template that you want to modify and then place it in the resources folder. Then, you have to modify the swaggerSources block in the build.gradle file by adding an extra configuration parameter to point to the template source, such as templateDir = file("${rootDir}/src/main/resources/ templates"). This is the place where you keep modified templates such as api. mustache. This will extend the OpenAPI Codegen templates. You can find all the templates inside the OpenAPI...
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