Book Image

Modern API Development with Spring 6 and Spring Boot 3 - Second Edition

By : Sourabh Sharma
1 (1)
Book Image

Modern API Development with Spring 6 and Spring Boot 3 - Second Edition

1 (1)
By: Sourabh Sharma

Overview of this book

Spring is a powerful and widely adopted framework for building scalable and reliable web applications in Java, complemented by Spring Boot, a popular extension to the framework that simplifies the setup and configuration of Spring-based applications. This book is an in-depth guide to harnessing Spring 6 and Spring Boot 3 for web development, offering practical knowledge of building modern robust web APIs and services. The book covers a wide range of topics that are essential for API development, including RESTful web service fundamentals, Spring concepts, and API specifications. It also explores asynchronous API design, security, designing user interfaces, testing APIs, and the deployment of web services. In addition to its comprehensive coverage, this book offers a highly contextual real-world sample app that you can use as a reference for building different types of APIs for real-world applications. This sample app will lead you through the entire API development cycle, encompassing design and specification, implementation, testing, and deployment. By the end of this book, you’ll have learned how to design, develop, test, and deploy scalable and maintainable modern APIs using Spring 6 and Spring Boot 3, along with best practices for bolstering the security and reliability of your applications and improving your application's overall functionality.
Table of Contents (21 chapters)
1
Part 1 – RESTful Web Services
7
Part 2 – Security, UI, Testing, and Deployment
12
Part 3 – gRPC, Logging, and Monitoring
16
Part 4 – GraphQL

Introducing REST APIs

An API is how a piece of code communicates with another piece of code. You might have already written and consumed APIs for your programs; for example, Java provides APIs through classes wrapped in different modules, such as collection, input/output, and streams.

Java’s SDK APIs allow one part of a program to communicate with another part of a program. You can write a function and then expose it with public access modifiers so that other classes can use it. That function signature is an API for that class. However, APIs that are exposed using these classes or libraries only allow internal communication inside a single application or an individual service. So, what happens when two or more applications (or services) want to communicate with each other, or, in other words, you would like to integrate two or more services? This is where system-wide APIs help us.

Historically, there were different ways to integrate one application with another – RPC, Simple Object Access Protocol (SOAP)-based services, and more. The integration of apps has become an integral part of software architectures, especially after the boom of the cloud and mobile phones. You now have social logins, such as Facebook, Google, and GitHub, which means you can develop your application even without writing an independent login module and get around security issues such as storing passwords securely.

These social logins provide APIs using REST and GraphQL. Currently, REST is the most popular, and it has become the standard for writing APIs for integration and web app consumption. We’ll also discuss GraphQL in detail in the final chapters of this book (in Chapter 13, Getting Started with GraphQL, and Chapter 14, GraphQL API Development and Testing).

REST stands for REpresentational State Transfer, which is a style of software architecture. Web services that adhere to the REST style are called RESTful web services. In the following sections, we will take a quick look at the history of REST to understand its fundamentals.

The history of REST

Before the adoption of REST, when the internet was just starting to become widely known and Yahoo and Hotmail were the popular mail and social messaging apps, there was no standard software architecture that offered a homogenous way to integrate with web applications. People were using SOAP-based web services, which, ironically, were not simple at all.

Then came the light. Roy Fielding, in his doctoral research, Architectural Styles and the Design of Network-Based Software Architectures (https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm), came up with REST in 2000. REST’s architecture style allowed any server to communicate with any other server over the network. It simplified communication and made integration easier. REST was made to work on top of HTTP, which enables it to be used all over the web and in internal networks.

eBay was the first to exploit REST-based APIs. It introduced the REST API with selected partners in November 2000. Later, Amazon, Delicious (a site-bookmarking web app), and Flickr (the photo-sharing app) started providing REST-based APIs. Then, Amazon Web Services (AWS) took advantage of Web 2.0 (with the invention of REST) and provided REST APIs to developers for AWS cloud consumption in 2006.

Later, Facebook, Twitter, Google, and other companies started using it. Nowadays (in 2023), you will hardly find any web applications that have been developed without a REST API. However, the GraphQL-based API for mobile apps is getting close in terms of popularity.

REST fundamentals

REST works on top of the HTTP protocol. Each URI works as an API resource. Therefore, we should use nouns as endpoints instead of verbs. RPC-style endpoints use verbs, for example, /api/v1/getPersons. In comparison, in REST, this endpoint could be simply written as /api/v1/persons. You must be wondering, then, how we can differentiate between the different actions performed on a REST resource. This is where HTTP methods help us. We can make our HTTP methods act as verbs, for example, GET, DELETE, POST (for creating), PUT (for modifying), and PATCH (for partial updating). We’ll discuss this in more detail later. For now, the getPerson RPC-style endpoint is translated into GET /api/v1/persons in REST.

Note

The REST endpoint is a unique URI that represents a REST resource. For example, https://demo.app/api/v1/persons is a REST endpoint. Additionally, /api/v1/persons is the endpoint path and persons is the REST resource.

Here, there is client and server communication. Therefore, REST is based on the client-server concept. The client calls the REST API and the server responds. REST allows a client (that is, a program, web service, or UI app) to talk to a remotely (or locally) running server (or web service) using HTTP requests and responses. The client sends an API command wrapped in an HTTP request to the web service. This HTTP request may contain a payload (or input) in the form of query parameters, headers, or request bodies. The called web service responds with a success/failure indicator and the response data wrapped inside the HTTP response. The HTTP status code normally denotes the status, and the response body contains the response data. For example, an HTTP status code of 200 OK normally represents success.

From a REST perspective, an HTTP request is self-descriptive and has enough context for the server to process it. Therefore, REST calls are stateless. States are either managed on the client side or on the server side. A REST API does not maintain its state. It only transfers states from the server to the client or vice versa. This is why it is called REpresentational State Transfer, or REST for short.

REST also makes use of HTTP cache control, which makes REST APIs cacheable. Therefore, the client can also cache the representation (that is, the HTTP response) because every representation is self-descriptive.

REST operates using three key components:

  • Resources and URIs
  • HTTP methods
  • HATEOAS

A sample REST call in plain text looks like the following:

GET /licenses HTTP/2Host: api.github.com

Here, the /licenses path denotes the licenses resource. GET is an HTTP method. 2 at the end of the first line denotes the HTTP protocol version. The second line shares the host to call.

GitHub responds with a JSON object. The status is 200 OK and the JSON object is wrapped in a response body, as follows:

HTTP/2 200 OKdate: Mon, 10 Jul 2023 17:44:04 GMT
content-type: application/json; charset=utf-8
server: GitHub.com
status: 200 OK
cache-control: public, max-age=60, s-maxage=60
vary: Accept, Accept-Encoding, Accept, X-Requested-With,
      Accept-Encoding  etag:W/"3cbb5a2e38ac6fc92b3d798667e
          828c7e3584af278aa314f6eb1857bbf2593ba"
… <bunch of other headers>
Accept-Ranges: bytes
Content-Length: 2037
X-GitHub-Request-Id: 1C03:5C22:640347:81F9C5:5F70D372
[
  {
    "key": "agpl-3.0",
    "name": "GNU Affero General Public License v3.0",
    "spdx_id": "AGPL-3.0",
    "url": "https://api.github.com/licenses/agpl-3.0",
    "node_id": "MDc6TGljZW5zZTE="
  },
  {
    "key": "apache-2.0",
    "name": "Apache License 2.0",
    "spdx_id": "Apache-2.0",
    "url": "https://api.github.com/licenses/apache-2.0",
    "node_id": "MDc6TGljZW5zZTI="
  },
  …
]

If you note the third line in this response, it tells you the value of the content type. It is good practice to have JSON as the content type for both the request and the response.

Now that we have familiarized ourselves with the fundamentals of REST, we are going to dive a bit deeper into REST’s first concept, resources and URIs, and learn what they are and how they are generally used.