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

Best practices for designing REST APIs

It is too early to talk about the best practices for implementing APIs. APIs are designed first and implemented later. Therefore, you’ll find design-related best practices mentioned in the next sections. You’ll also find best practices for going forward during REST API implementation.

Using nouns and not verbs when naming a resource in the endpoint path

We previously discussed HTTP methods. HTTP methods use verbs. Therefore, it would be redundant to use verbs yourself, and it would make your call look like an RPC endpoint, for example, GET /getlicenses. In REST, we should always use the resource name because, according to REST, you transfer the states and not the instructions. For example, let’s take another look at the GitHub license API, which retrieves licenses. It is GET /licenses. That is perfect. Let’s assume that if you use verbs for this endpoint, then it will be GET /getlicenses. It will still work, but semantically, it doesn’t follow REST because it conveys the processing instruction rather than state transfer. Therefore, only use resource names.

However, GitHub’s public API only offers read operations on the licenses resource, out of all the CRUD operations. If we need to design the rest of the operations, their paths should look like the following:

  • POST /licenses: This is for creating a new license.
  • PATCH /licenses/{license_key}: This is for partial updates. Here, the path has a parameter (that is, an identifier) that makes the path dynamic. Here, the license key is a unique value in the license collection and is being used as an identifier. Each license will have a unique key. This call should make the update in the given license. Please remember that GitHub uses PUT for the replacement of the resource.
  • DELETE /licenses/{license_key}: This is for retrieving license information. You can try this with any licenses that you receive in the response to the GET /licenses call. One example is GET /licenses/agpl-3.0.

You can see how having a noun in the resource path with the HTTP methods sorts out any ambiguity.

Using the plural form for naming the collection resource in the endpoint path

If you observe the GitHub license API, you might find that a resource name is given in the plural form. It is a good practice to use the plural form if the resource represents a collection. Therefore, we can use /licenses instead of /license. A GET call returns the collection of licenses. GitHub doesn’t allow create, update, or delete public operations on a licensed resource. Hypothetically, if it allowed this, then a POST call would create a new license in the existing license collection. Similarly, for DELETE and PATCH calls, a license key is used to identify the specific license for performing delete and minor update operations respectively.

Using hypermedia (HATEOAS)

Hypermedia (that is, links to other resources) makes the REST client’s job easier. There are two advantages if you provide explicit URL links in a response. First, the REST client is not required to construct the REST URLs on their own. Second, any upgrade in the endpoint path will be taken care of automatically and this, therefore, makes upgrades easier for clients and developers

Versioning your APIs

The versioning of APIs is key for future upgrades. Over time, APIs keep changing, and you may have customers who are still using an older version. Therefore, you need to support multiple versions of APIs.

There are different ways you can version your APIs:

  • Using headers: The GitHub API uses this approach. You can add an Accept header that tells you which API version should serve the request; for example, consider the following:
    Accept: application/vnd.github.v3+json

This approach gives you the advantage of setting the default version. If there is no Accept header, it should lead to the default version. However, if a REST client that uses a versioning header is not changed after a recent upgrade of APIs, it may break the functionality. Therefore, it is recommended that you use a versioning header.

  • Using an endpoint path: In this approach, you add a version in the endpoint path itself; for example, https://demo.app/api/v1/persons. Here, v1 denotes that version 1 is being added to the path itself.

You cannot set default versioning out of the box. However, you can overcome this limitation by using other methods, such as request forwarding. Clients always use the intended versions of the APIs in this approach.

Based on your preferences and views, you can choose either of the preceding approaches for versioning. However, the important point is that you should always use versioning.

Nesting resources

Consider this very interesting question: how are you going to construct the endpoint for resources that are nested or have a certain relationship? Let’s take a look at some examples of customer resources from an e-commerce perspective:

  • GET /customers/1/addresses: This returns the collection of addresses for customer 1
  • GET /customers/1/addresses/2: This returns the second address of customer 1
  • POST /customers/1/addresses: This adds a new address to customer 1’s addresses
  • PUT /customers/1/addresses/2: This replaces the second address of customer 1
  • PATCH /customers/1/addresses/2: This partially updates the second address of customer 1
  • DELETE /customers/1/addresses/2: This deletes the second address of customer 1

So far so good. Now, can we have an altogether separate address resource endpoint (GET /addresses/2)? It makes sense, and you can do that if there is a relationship that requires it; for example, orders and payments. Instead of /orders/1/payments/1, you might prefer a separate /payments/1 endpoint. In the microservice world, this makes more sense; for instance, you would have two separate RESTful web services for both orders and payments.

Now, if you combine this approach with hypermedia, it makes things easier. When you make a REST API request to customer 1, it will provide the customer 1 data and address links as hypermedia (that is, links). The same applies to orders. For orders, the payment link will be available as hypermedia.

However, in some cases, you might wish to have a complete response in a single request rather than using the hypermedia-provided URLs to fetch the related resource. This reduces your web hits. However, there is no rule of thumb. For a flag operation, it makes sense to use the nested endpoint approach; for example, PUT /gist/2/star (which adds a star) and DELETE /gist/2/star (which undoes the star) in the case of the GitHub API.

Additionally, in some scenarios, you might not find a suitable resource name when multiple resources are involved, for example, in a search operation. In that case, you should use a direct/search endpoint. This is an exception.

Securing APIs

Securing your API is another expectation that requires diligent attention. Here are some recommendations:

  • Always use HTTPS for encrypted communication.
  • Always look for OWASP’s top API security threats and vulnerabilities. These can be found on their website (https://owasp.org/www-project-api-security/) or their GitHub repository (https://github.com/OWASP/API-Security).
  • Secure REST APIs should have authentication in place. REST APIs are stateless; therefore, REST APIs should not use cookies or sessions. Instead, they should be secured using JWT or OAuth 2.0-based tokens.

Maintaining documentation

Documentation should be easily accessible and up to date with the latest implementation with their respective versioning. It is always good to provide sample code and examples. It makes the developer’s integration job easier.

A change log or a release log should list all the affected libraries, and if some APIs are deprecated, then replacement APIs or workarounds should be elaborated upon inside the documentation.

Complying with recommended status codes

We have already learned about status codes in the Exploring HTTP methods and status codes section. Please follow the same guidelines discussed there.

Ensuring caching

HTTP already provides a caching mechanism. You just have to provide additional headers in the REST API response. Then, the REST client makes use of the validation to make sure whether to make a call or use the cached response. There are two ways to do this:

  • ETag: ETag is a special header value that contains the hash or checksum value of the resource representation (that is, the response object). This value must change with respect to the response representation. It will remain the same if the resource response doesn’t change. Now, the client can send a request with another header field, called If-None-Match, which contains the ETag value. When the server receives this request and finds that the hash or checksum value of the resource representation value is different from If-None-Match, only then should it return the response with a new representation and this hash value in the ETag header. If it finds them to be equal, then the server should simply respond with a 304 (Not Modified) status code.
  • Last-Modified: This approach is identical to the ETag way. However, instead of using the hash or checksum, it uses the timestamp value in RFC-1123 (http://www.ietf.org/rfc/rfc1123.txt) in the format: Last-Modified: Wed, 21 Oct 2015 07:28:00 GMT. It is less accurate than ETag and should only be used as a fallback.

In the Last-Modified approach, the client sends the If-Modified-Since header with the value received in the Last-Modified response header. The server compares the resource-modified timestamp value with the If-Modified-Since header value and sends a 304 status if there is a match; otherwise, it sends the response with a new Last-Modified header.

Maintaining the rate limit

Maintaining the rate limit is important if you want to prevent the overuse of APIs. The HTTP status code 429 Too Many Requests is used when the rate limit is infringed. Currently, there is no standard to communicate any warning to the client before the rate limit goes over. However, there is a popular way to communicate about it using response headers. These response headers are as follows:

  • X-Ratelimit-Limit: The number of allowed requests in the current period, for example, X-Ratelimit-Limit: 60.
  • X-Ratelimit-Remaining: The number of remaining requests in the current period, for example, X-Ratelimit-Remaining: 55.
  • X-Ratelimit-Reset: The number of seconds left in the current period, for example, X-Ratelimit-Reset: 1601299930.
  • X-Ratelimit-Used: The number of requests used in the current period, for example, X-Ratelimit-Used: 5. This information then might be used by the client to keep track of the total number of available API calls for the given period.

So far, we have discussed various concepts related to REST. Next, let me introduce you to the app we will be building in this book using these concepts.