spring hateoas что это

Создание Hypermedia RESTful Web-сервиса

В этом уроке освещается процесс создания «hello world» Hypermedia Driven REST web-сервиса c использованием Spring.

Гипермедиа является важной частью REST. Это позволяет вам создавать сервисы, которые значительно отделяют клиента и сервер, позволяя им развиваться независимо друг от друга. Представления возвращают REST ресурсы, содержащие ссылки, которые указывают на дополнительные ресурсы, с которыми клиент должен взаимодействовать. Поэтому дизайн представления имеет решающее значение в разработке всего сервиса.

Что вы создадите

Вы создадите гипермедиа REST сервис с использованием Spring HATEOAS, библиотекой с API, которую вы можете использовать для создания ссылок к Spring MVC контроллерам, построения представлений ресурсов и управлением тем, как они будут отображены с поддержкой гипермедиа форматов, таких как HAL.

Сервис будет принимать HTTP GET запросы вида:

А в ответ возвращает JSON представление с сообщением, дополненным простейшим гипермедиа элементом, ссылкой на себя:

Ответ уже означает, что вы можете модифицировать сообщение с дополнительным параметром name в строке запроса:

Параметр name переопределяет значение по умолчанию «World» и отражается в ответе:

Что вам потребуется

Как проходить этот урок

Как и большинство уроков по Spring, вы можете начать с нуля и выполнять каждый шаг, либо пропустить базовые шаги, которые вам уже знакомы. В любом случае, вы в конечном итоге получите рабочий код.

Чтобы начать с нуля, перейдите в Настройка проекта.

Настройка проекта

Для начала вам необходимо настроить базовый скрипт сборки. Вы можете использовать любую систему сборки, которая вам нравится для сборки проетов Spring, но в этом уроке рассмотрим код для работы с Gradle и Maven. Если вы не знакомы ни с одним из них, ознакомьтесь с соответсвующими уроками Сборка Java-проекта с использованием Gradle или Сборка Java-проекта с использованием Maven.

Создание структуры каталогов

Создание файла сборки Gradle

Ниже представлен начальный файл сборки Gradle. Файл pom.xml находится здесь. Если вы используете Spring Tool Suite (STS), то можете импортировать урок прямо из него.

Spring Boot gradle plugin предоставляет множество удобных возможностей:

Создание класса представления ресурса

Теперь, когда вы настроили проект, вы можете создать ваш web-сервис.

Начнем с процесса взаимодействия с сервисом.

Сервис будет предоставлять доступ к ресурсу /greeting через GET запросы с необязательным параметром name в строке запроса. GET запрос должен возвращать 200 OK ответ с JSON в теле представления приветствия.

content является текстовым представлением приветствия. _links элемент содержит список ссылок, в данном случае ровно одну с отношением типа rel и href атрибутом, указывающим на ресурс.

Вы просто создаете POJO, наследуясь от ResourceSupport и добавляете поле и метод получения содержимого, а также конструктор с аргументом этого поля:

Далее вы создадите контроллер ресурса, который будет обрабатывать эти приветствия.

Создание контроллера ресурса

Контроллер краток и прост, но там много чего происходит. Давайте подробнее рассмотрим шаг за шагом.

@RequestMapping аннотация гарантирует, что HTTP запросы к /greeting будут обработаны greeting() методом.

Создание приложения исполняемым

Несмотря на то, что пакет этого сервиса может быть в составе web-приложения и WAR файлов, более простой подход, продемонстрированный ниже создает отдельное самостоятельное приложение. Вы упаковываете все в единый, исполняемый JAR-файл, который запускается через хорошо знакомый старый main() Java-метод. Попутно, вы используете поддержку Spring для встроенного Tomcat контейнера сервлетов как HTTP среду выполнения вместо развертывания на сторонний экземпляр.

Сборка исполняемого JAR

Вы можете собрать единый исполняемый JAR-файл, который содержит все необходимые зависимости, классы и ресурсы. Это делает его легким в загрузке, версионировании и развертывании сервиса как приложения на протяжении всего периода разработки, на различных средах и так далее.

Затем вы можете запустить JAR-файл:

Если вы используете Gradle, вы можете запустить ваш сервис из командной строки:

Как вариант, вы можете запустить ваш сервис напрямую из Gradle примерно так:

Данные по логгированию отображаются. Сервис должен быть поднят и запущен через несколько секунд.

Тестирование сервиса

Теперь, когда сервис поднят, зайдите по адресу http://localhost:8080/greeting, где вы увидите:

Передайте в запрос строковый параметр name http://localhost:8080/greeting?name=User. обратите внимание как значение атрибута content изменится с «Hello, World!» на «Hello, User!» и атрибут href ссылки self также изменится:

Это изменение демонтрирует, что соглашение @RequestParam в GreetingController работает как и ожидалось. Параметру name дано значение по умолчанию «World», но всегда можно явно переопределить через строку запроса.

Поздравляем! Вы только что разработали гипермедиа RESTful сервис, используя Spring HATEOAS.

Источник

An Intro to Spring HATEOAS

Last modified: February 25, 2021

Get started with Spring 5 and Spring Boot 2, through the reference Learn Spring course:

Get started with Spring 5 and Spring Boot 2, through the reference Learn Spring course:

1. Overview

This article explains the process of creating hypermedia-driven REST web service using the Spring HATEOAS project.

2. Spring-HATEOAS

The Spring HATEOAS project is a library of APIs that we can use to easily create REST representations that follow the principle of HATEOAS (Hypertext as the Engine of Application State).

Generally speaking, the principle implies that the API should guide the client through the application by returning relevant information about the next potential steps, along with each response.

In this article, we’re going to build an example using Spring HATEOAS with the goal of decoupling the client and server, and theoretically allowing the API to change its URI scheme without breaking clients.

3. Preparation

First, let’s add the Spring HATEOAS dependency:

If we’re not using Spring Boot we can add the following libraries to our project:

As always, we can search the latest versions of the starter HATEOAS, the spring-hateoas and the spring-plugin-core dependencies in Maven Central.

Next, we have the Customer resource without Spring HATEOAS support:

And we have a controller class without Spring HATEOAS support:

Finally, the Customer resource representation:

4. Adding HATEOAS Support

In a Spring HATEOAS project, we don’t need to either look up the Servlet context nor concatenate the path variable to the base URI.

Читайте также:  аиу какой сезон о чем

Instead, Spring HATEOAS offers three abstractions for creating the URI – RepresentationModel, Link, and WebMvcLinkBuilder. We can use these to create the metadata and associate it to the resource representation.

4.1. Adding Hypermedia Support to a Resource

The project provides a base class called RepresentationModel to inherit from when creating a resource representation:

The Customer resource extends from the RepresentationModel class to inherit the add() method. So once we create a link, we can easily set that value to the resource representation without adding any new fields to it.

4.2. Creating Links

Spring HATEOAS provides a Link object to store the metadata (location or URI of the resource).

First, we’ll create a simple link manually:

The Link object follows the Atom link syntax and consists of a rel which identifies relation to the resource and href attribute which is the actual link itself.

Here’s how the Customer resource looks now that it contains the new link:

The URI associated with the response is qualified as a self link. The semantics of the self relation is clear – it’s simply the canonical location the resource can be accessed at.

4.3. Creating Better Links

Another very important abstraction offered by the library is the WebMvcLinkBuilder – which simplifies building URIs by avoiding hard-coded the links.

The following snippet shows building the customer self-link using the WebMvcLinkBuilder class:

5. Relations

In the previous section, we’ve shown a self-referencing relation. However, more complex systems may involve other relations as well.

For example, a customer can have a relationship with orders. Let’s model the Order class as a resource as well:

At this point, we can extend the CustomerController with a method that returns all orders of a particular customer:

Our method returns a CollectionModel object to comply with the HAL return type, as well as a “_self” link for each of the orders and the full list.

An important thing to notice here is that the hyperlink for the customer orders depends on the mapping of getOrdersForCustomer() method. We’ll refer to these types of links as method links and show how the WebMvcLinkBuilder can assist in their creation.

6. Links to Controller Methods

The WebMvcLinkBuilder offers rich support for Spring MVC Controllers. The following example shows how to build HATEOAS hyperlinks based on the getOrdersForCustomer() method of the CustomerController class:

The methodOn() obtains the method mapping by making dummy invocation of the target method on the proxy controller and sets the customerId as the path variable of the URI.

7. Spring HATEOAS in Action

Let’s put the self-link and method link creation all together in a getAllCustomers() method:

Next, let’s invoke the getAllCustomers() method:

And examine the result:

Within each resource representation, there is a self link and the allOrders link to extract all orders of a customer. If a customer doesn’t have orders, then the link for orders won’t appear.

This example demonstrates how Spring HATEOAS fosters API discoverability in a rest web service. If the link exists, the client can follow it and get all orders for a customer:

8. Conclusion

In this tutorial, we’ve discussed how to build a hypermedia-driven Spring REST web service using the Spring HATEOAS project.

In the example, we see that the client can have a single entry point to the application and further actions can be taken based on the metadata in the response representation.

This allows the server to change its URI scheme without breaking the client. Also, the application can advertise new capabilities by putting new links or URIs in the representation.

Finally, the full implementation of this article can be found in the GitHub project.

Источник

Spring HATEOAS

Spring HATEOAS provides some APIs to ease creating REST representations that follow the HATEOAS principle when working with Spring and especially Spring MVC. The core problem it tries to address is link creation and representation assembly.

Features

Model classes for link, resource representation models

Link builder API to create links pointing to Spring MVC controller methods

Support for hypermedia formats like HAL

Spring Boot Config

Spring Boot will do the following:

Configure HAL support

Register support for entity links

Wire up message converter support.

Quickstart Your Project

Documentation

1.4.0 CURRENT GA Reference Doc. API Doc.
1.5.0-SNAPSHOT SNAPSHOT Reference Doc. API Doc.
1.4.1-SNAPSHOT SNAPSHOT Reference Doc. API Doc.
1.3.7-SNAPSHOT SNAPSHOT Reference Doc. API Doc.
1.3.6 GA Reference Doc. API Doc.
1.2.12-SNAPSHOT SNAPSHOT Reference Doc. API Doc.
1.2.11 GA Reference Doc. API Doc.

OSS support

Free security updates and bugfixes with support from the Spring community. See VMware Tanzu OSS support policy.

Commercial support

Business support from Spring experts during the OSS timeline, plus extended support after OSS End-Of-Life.
Publicly available releases for critical bugfixes and security issues when requested by customers.

Future release

Generation not yet released, timeline is subject to changes.

About commercial support (*)

A few examples to try out:

Get ahead

VMware offers training and certification to turbo-charge your progress.

Get support

Spring Runtime offers support and binaries for OpenJDK™, Spring, and Apache Tomcat® in one simple subscription.

Upcoming events

Check out all the upcoming events in the Spring community.

Источник

Spring HATEOAS: веб-сервисы RESTful, управляемые гипермедиа

С помощью HATEOAS мы можем предоставить дополнительную информацию в одном вызове API. В этой статье мы будем создавать веб-сервис RESTful, управляемый гипермедиа, на Java и Spring HATEOAS.

Вступление

API-интерфейсы REST являются гибкими и позволяют разработчикам создавать отдельные системы. С развитием архитектуры микросервисов – REST стал еще более зрелым, поскольку микросервисы могут создаваться независимо от языка или структуры, используемой в приложении.

Что такое HATEOAS?

Находясь в центре внимания, внедряются различные методы архитектуры, ориентированные на основы REST.

Читайте также:  какие специи нужны для плова со свининой в мультиварке

Гипермедиа как механизм состояния приложения (HATEOAS) – это архитектурный подход для повышения удобства использования API REST для приложений, использующих API.

Основная цель HATEOAS – предоставить дополнительную информацию в ответах REST API, чтобы пользователи API могли получать дополнительные сведения о конечных точках из одного вызова. Это позволяет пользователям создавать свои системы с помощью динамических вызовов API, перемещаясь от одной конечной точки к другой, используя информацию, полученную в результате каждого вызова.

Чтобы лучше понять это, взгляните на следующий ответ API:

Помимо получения подробной информации о враче, ответ API также предоставляет дополнительную информацию в виде ссылок. Например, прикреплена ссылка для выборки всех пациентов одного врача.

Весенняя НЕНАВИСТЬ

Spring HATEOAS предоставляет библиотеки для простой реализации архитектуры HATEOAS в приложении Spring. Используя API Spring HATEOAS, ссылки могут быть созданы и возвращены как часть объекта ответа API.

Весенняя НЕНАВИСТЬ К зависимостям

Используя Maven, добавить Spring HATEOAS так же просто, как включить зависимости:

В качестве альтернативы, используя Gradle, вы можете добавить:

Зависимости Spring Boot HATEOAS

Еще проще, для приложений Spring Boot вы можете использовать зависимость spring-boot-starter-hateoas Maven:

Аналогично, если вы используете Gradle, вы можете просто добавить:

Использование spring-boot-starter-hateoas зависимости включает spring-hateoas и spring-boot-starter-web зависимости, поэтому, естественно, никакие другие стартеры не требуются.

Строительные блоки Spring HATEOAS

Основными строительными блоками для Spring HATEOAS являются Link s и Модель представления s (контейнер для коллекции Link s).

Давайте уделим немного времени объяснению каждого из них, прежде чем применять их в рабочей демонстрации.

Связи

Неизменяемый объект Link используется для хранения метаданных ресурса (URI или местоположения), и конечный пользователь может перейти к ресурсам, которые обогащают наш ответ API. Базовая ссылка с URI ресурса может выглядеть следующим образом:

Почему ресурс указывает на себя?

Возвращенные ресурсы могут не быть полным представлением самих себя. У врача может быть список пациентов, но мы можем не захотеть возвращать его по умолчанию.

Если затем мы захотим взглянуть на список врачей, мы можем перейти к нему по ссылке.

Модели представления

Модель представления | действует как корневой класс для всех других классов моделей Spring HATEOAS. Он содержит коллекцию Ссылок и предоставляет метод для их добавления/удаления.

Модель сущности : Модель сущности используется для представления ресурса, соответствующего одному объекту. Вы можете обернуть свой ресурс моделью сущности и передать его вызывающей службе или вернуть его через конечную точку REST.

Модель подкачки : Кроме того, поскольку многие конечные точки API REST возвращают ответы, которые являются коллекциями с возможностью просмотра страниц, Spring HATEOAS предоставляет Модель страницы для представления таких ресурсов.

Создание Ссылок

Давайте создадим образец ресурса, который расширяет Модель представления класса:

На данный момент у нашей модели Doctor есть только свойство id и список пациентов. Далее мы добавим Ссылку на ресурс, которая укажет ресурс на самого себя.

Объект Связи

Spring HATEOAS Ссылка объекты принимают Строку аргументы для указания URI и связи между сущностями. В основном это атрибуты href и rel :

Когда возвращается объект doctor (как показано в демонстрационном приложении в последующих разделах), тело ответа будет содержать:

Компоновщик MVC

Git Essentials

Ознакомьтесь с этим практическим руководством по изучению Git, содержащим лучшие практики и принятые в отрасли стандарты. Прекратите гуглить команды Git и на самом деле изучите это!

Давайте воссоздадим ссылку из предыдущего примера с помощью WebMvcLinkBuilder :

Здесь мы используем более программный подход к созданию ссылок. Он указывает на метод get Doctor By Id() внутри класса Контроллера Doctor. Поскольку он указывает на себя, мы используем метод withSelfRel() для указания связи.

В качестве альтернативы мы могли бы использовать метод with Real() и передать строку с другим отношением.

Реляционные Связи

Обратите внимание, что мы не указали никакого URL-адреса при создании ссылки. Spring HATEOAS может извлекать информацию из конструктора ссылок и генерировать URL-адрес на основе используемых нами сопоставлений.

Конфигурация

Демонстрационное приложение

Учитывая все сказанное, давайте напишем простое приложение Spring с поддержкой HATEOAS, перейдя в Spring Initializr и создав пустое приложение Spring Boot с зависимостью Spring HATEOAS ( spring-boot-hateoas-starter ):

Создание ресурса

Давайте создадим модель для Врача :

Поскольку класс Врач имеет отношения с пациентами, давайте также создадим модель Пациент :

С помощью этого мы создали ресурс. При извлечении ресурсов мы будем ожидать либо один ресурс, либо набор ресурсов. Как указывалось ранее, мы завернем их в Модель сущности или Модель коллекции соответственно.

Получение одного ресурса

Давайте сначала реализуем функциональность выбора одного врача. Поскольку мы ожидаем, что вызов API вернет один ресурс, мы завернем наш ответ в модель сущности класс:

В конце метода мы завернули ваш Доктор объект в Модель сущности класс, и эта Модель сущности возвращается в качестве ответа:

Получение Нескольких Ресурсов

Как только все ссылки будут добавлены, мы завернем коллекцию объектов Doctor в модель Коллекции и вернем ее:

Как вы можете видеть из выходных данных, просто сделав один звонок, пользователь может обнаружить дополнительную информацию, которой в противном случае не было бы.

Вывод

Spring HATEOAS предоставляет необходимые библиотеки и инфраструктуру для реализации архитектуры HATEOAS в приложениях на базе Spring.

Как видно из выходных данных, пользователи могут получить дополнительную информацию из одного вызова REST. Используя эту информацию, проще создавать динамические клиенты REST.

В этой статье мы обсудили, как работает HATEOAS, его реализацию Весной и закончили созданием простого приложения для демонстрации концепций.

Источник

Spring HATEOAS

As part of the REST with Spring Series, this post is going to cover Spring HATEOAS. We are going to talk about the HATEOAS in REST driven APIs.

Introduction

HATEOAS (Hypermedia as the Engine of Application State) is a constraint of the REST application architecture. A hypermedia driven REST API provides information to help to navigate through the API dynamically. This is done by passing hypermedia links with the responses.HATEOAS is a fundamental concept to create Discoverable REST APIs.To get a better clarity, let’s take a look at the sample response.

Читайте также:  Что такое модифицированная синусоида

In the above example, API response contains few links used by the API client for navigation. There are two important points in the links section. Let’s take a closer looks at these two points.

1. Spring HATEOAS

Spring HATEOAS provides a set of API and tools for creating REST APIs that follow the HATEOAS principle. Here are some of the features provides by Spring HATEOAS.

The basic principle of HATEOAS is to help the client navigate through the API by returning the relevant information as the links in the response. Take a look at above example where response contains links for the project description. In this article, we are going to create Spring HATEOAS driven REST API based on Spring Boot.

2. HATEOAS and RESTful Web Services

Hypermedia is a very important part of REST architecture. This approach allows the REST client and API to evolve independently without breaking it. As part of the design, REST API returns data along with the links to the related resources. This helps the client to navigate the API without building the URL’s (which can break if API structure change ). Let’s take a closer look at some of the benefits of using the HATEOAS while working on the REST API.

3. Maven

In order to enable support for Spring HATEOAS, we need to add “spring-boot-starter-hateoas” in the pom.xml file.

4. Example Resource

To better explain the Spring HATEOAS and REST API, let’s create our Product Resources. We are going to build hypermedia URL’s based on this resource.

With no HATEOAS support, for a simple REST API, the client API will receive the following response.

There is no issue in the above response but if client API needs to create the URL’s, API needs to find out details about the host, context etc to build the correct URL. This can become more complicated if there is a change happened to the API structure (Client API need to rewrite the URL building logic).To handle such use cases, it is really critical and important to add hypermedia support in your REST API.

5. Enable Spring HATEOAS

To enable Spring HATEOAS support for our resource, we are going to use the base class ResourceSupport available as part of the Spring support for HATEOAS. This base class allows us to add instances of Link that is useful while creating the _links element. This is how our Product resource looks like.

The ResourceSupport class provides add() method for link building. Let’s see this in more detail in the next section.

5.1 Creating Links

Spring HATEOAS provides a Link object to store the metadata. There are two ways to create a link while working on the RESTful API’s. We can create a simple Link object by passing the URI in the constructor.

Spring HATEOAS provides another option to build links using the ControllerLinkBuilder.This is how it looks like:

This looks really simple but there is a lot of going on in the above method. The interesting part of the creation of links which points to our controller method. Both linkTo(…) and methodOn(…) are static methods on ControllerLinkBuilder that allow you to fake a method invocation on the controller. The final output is the exact URI for our method. This is how the response of our method looks like:

To add more details, let’s take a look at the few important points:

6. Spring HATEOAS and Relations

Above example was very simple but real life use cases come with complex relationships and we want to make sure that client REST API still have the ways to navigate without creating or assuming about the resource URLs.To make this more interesting, let’s assume that we also support product review with the following details:

This is how our ProductReview class looks like:

Let’s extend our product controller by adding one more method to fetch reviews for a given product:

There are a few important points to keep in the mind:

6.1 The ControllerLinkBuilder

HATEOAS API provides a powerful support to build Link pointing to the Spring MVC or REST controllers. The ControllerLinkBuilder uses Spring’s ServletUriComponentsBuilder under the hood to obtain the basic URI information from the current request. Let’s take a look at the previous example for better understanding:

In the above example, the method methodOn(…) creates a proxy of the controller class that is recording the method invocation and exposes it in a proxy created for the return type of the method. For more details read Link builder.

7. Running Example

In the final step, let’s see our work in action. This is how our controller looks like

To get all the products, just run the following URL in the browser or in the curl request: http://localhost:8080/products.This is how API respond.

There are a few important points we should be looking at:

As a REST client, we have al the details to navigate to the different sections without creating those URLs. If you click on the product URL, this is what you can expect:

Summary

In this post, we cover Spring HATEOAS and how to build hypermedia-driven Spring REST web service. Building a hypermedia feature for your REST API is really powerful and provides flexibility to the REST client to navigate and build the features without creating or thinking out the URL’s. This approach also provides flexibility to the server to change the URL structure or introducing new features without breaking the client API. It also let both clients as well as server API to evolve independently.

Source code for this post is available on the Github.

Источник

Информ портал о технике и не только