Spring REST and HAL Browser – Spring REST和HAL浏览器

最后修改: 2018年 7月 19日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll be discussing what HAL is and why it’s useful, before introducing the HAL browser.

在本教程中,在介绍HAL浏览器之前,我们将讨论什么是HAL以及为什么它很有用

We’ll then use Spring to build a simple REST API with a few interesting endpoints and populate our database with some test data.

然后,我们将使用Spring建立一个简单的REST API,其中有几个有趣的端点,并将一些测试数据填充到我们的数据库中。

Finally, using the HAL browser, we’ll explore our REST API and discover how to traverse the data contained within.

最后,使用HAL浏览器,我们将探索我们的REST API,并发现如何遍历其中的数据。

2. HAL and the HAL Browser

2.HAL和HAL浏览器

JSON Hypertext Application Language, or HAL, is a simple format that gives a consistent and easy way to hyperlink between resources in our API. Including HAL within our REST API makes it much more explorable to users as well as being essentially self-documenting.

JSON超文本应用语言,或称HAL,是一种简单的格式,为我们的API中的资源之间的超链接提供了一种一致且简单的方法。在我们的REST API中包含HAL,这使得用户更容易探索,而且基本上是自我记录。

It works by returning data in JSON format which outlines relevant information about the API.

它通过返回JSON格式的数据来工作,这些数据概述了关于API的相关信息。

The HAL model revolves around two simple concepts.

HAL模型围绕着两个简单的概念。

Resources, which contain:

资源,其中包含。

  • Links to relevant URIs
  • Embedded Resources
  • State

Links:

链接:

  • A target URI
  • A relation, or rel, to the link
  • A few other optional properties to help with depreciation, content negotiation, etc

The HAL browser was created by the same person who developed HAL and provides an in-browser GUI to traverse your REST API.

HAL浏览器是由开发HAL的同一个人创建的,提供了一个浏览器内的GUI来遍历你的REST API

We’ll now build a simple REST API, plug in the HAL browser and explore the features.

现在我们将建立一个简单的REST API,插入HAL浏览器并探索其功能。

3. Dependencies

3.依赖性

Below is the single dependency needed to integrate the HAL browser into our REST API. You can find the rest of the dependencies for the API in the GitHub code.

下面是将HAL浏览器集成到我们的REST API中所需的单个依赖项。您可以在GitHub代码中找到该API的其余依赖项。

Firstly, the dependency for Maven-based projects:

首先,基于Maven的项目的依赖性

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-rest-hal-explorer</artifactId>
    <version>3.4.1.RELEASE</version>
</dependency>

If you’re building with Gradle, you can add this line to your build.gradle file:

如果你用Gradle构建,你可以在你的build.gradle文件中添加这一行。

compile group: 'org.springframework.data', name: 'spring-data-rest-hal-explorer', version: '3.4.1.RELEASE'

4. Building a Simple REST API

4.构建一个简单的REST API

4.1. Simple Data Model

4.1.简单的数据模型

In our example, we’ll be setting up a simple REST API to browse different books in our library.

在我们的例子中,我们将设置一个简单的REST API来浏览我们图书馆中的不同书籍。

Here, we define a simple book entity which contains appropriate annotations so that we can persist the data with Hibernate:

在这里,我们定义了一个简单的图书实体,其中包含适当的注释,这样我们就可以用Hibernate来持久化数据。

@Entity
public class Book {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private long id;

  @NotNull
  @Column(columnDefinition = "VARCHAR", length = 100)
  private String title;

  @NotNull
  @Column(columnDefinition = "VARCHAR", length = 100)
  private String author;

  @Column(columnDefinition = "VARCHAR", length = 1000)
  private String blurb;

  private int pages;

  // usual getters, setters and constructors

}

4.2. Introducing a CRUD Repository

4.2.引入CRUD存储库

Next, we’ll need some endpoints. To do this, we can leverage the PagingAndSortingRepository and specify that we want to get data from our Book entity.

接下来,我们将需要一些端点。为此,我们可以利用PagingAndSortingRepository并指定我们要从我们的Book实体获取数据。

This Class provides simple CRUD commands, as well as paging and sorting capabilities right out of the box:

该类提供简单的CRUD命令,以及分页和排序功能,开箱即用。

@Repository
public interface BookRepository extends PagingAndSortingRepository<Book, Long> {

    @RestResource(rel = "title-contains", path="title-contains")
    Page<Book> findByTitleContaining(@Param("query") String query, Pageable page);

    @RestResource(rel = "author-contains", path="author-contains", exported = false)
    Page<Book> findByAuthorContaining(@Param("query") String query, Pageable page);
}

If this looks a bit strange, or if you’d like to know more about Spring Repositories, you can read more here.

如果这看起来有点奇怪,或者你想了解有关Spring Repositories的更多信息,你可以在这里阅读更多信息

We’ve extended the repository by adding two new endpoints:

我们通过添加两个新的端点来扩展资源库。

  • findByTitleContaining – returns books that contain the query included in the title
  • findByAuthorContaining – returns books from the database where the author of a book contains the query

Note that our second endpoint contains the export = false attribute. This attribute stops the HAL links being generated for this endpoint, and won’t be available via the HAL browser.

注意,我们的第二个端点包含export = false 属性。这个属性停止为这个端点生成HAL链接,并且将不能通过HAL浏览器使用。

Finally, we’ll load our data when Spring is started by defining a class which implements the ApplicationRunner interface. You can find the code on GitHub.

最后,我们将通过定义一个实现ApplicationRunner接口的类,在Spring启动时加载我们的数据。你可以在GitHub上找到这些代码。

5. Installing the HAL Browser

5.安装HAL浏览器

The setup for the HAL browser is remarkably easy when building a REST API with Spring. As long as we have the dependency, Spring will auto-configure the browser, and make it available via the default endpoint.

用Spring构建REST API时,HAL浏览器的设置非常简单。只要我们有依赖关系,Spring就会自动配置浏览器,并通过默认的端点使其可用。

All we need to do now is press run and switch to the browser. The HAL browser will then be available on http://localhost:8080/

现在我们需要做的就是按下运行键,切换到浏览器。然后,HAL浏览器将可在http://localhost:8080/上使用。

6. Exploring Our REST API With the HAL Browser

6.用HAL浏览器探索我们的REST API

The HAL browser is broken down into two parts – the explorer and the inspector. We’ll break down and explore each section separately.

HAL浏览器分为两部分–探索器和检查器。我们将对每个部分分别进行分解和探讨。

6.1. The HAL Explorer

6.1.HAL浏览器

As it sounds, the explorer is devoted to exploring new parts of our API relative to the current endpoint. It contains a search bar, as well as text boxes to display Custom Request Headers and Properties of the current endpoint.

听起来,探索器是专门用来探索我们的API相对于当前端点的新部分的。它包含一个搜索栏,以及用于显示当前端点的自定义请求头和属性的文本框。

Below these, we have the links section and a clickable list of Embedded Resources.

在这些下面,我们有链接部分和一个可点击的嵌入式资源列表。

6.2. Using Links

6.2.使用链接

If we navigate to our /books endpoint we can view the existing links:

如果我们导航到我们的/books 端点,我们可以查看现有的链接。

Links-1

These links are generated from the HAL in the adjacent section:

这些链接是由相邻部分的HAL生成的。

"_links": {
    "first": {
      "href": "http://localhost:8080/books?page=0&size=20"
    },
    "self": {
      "href": "http://localhost:8080/books{?page,size,sort}",
      "templated": true
    },
    "next": {
      "href": "http://localhost:8080/books?page=1&size=20"
    },
    "last": {
      "href": "http://localhost:8080/books?page=4&size=20"
    },
    "profile": {
      "href": "http://localhost:8080/profile/books"
    },
    "search": {
      "href": "http://localhost:8080/books/search"
    }
  },

If we move to the search endpoint, we can also view the custom endpoints we created using the PagingAndSortingRepository:

如果我们移动到搜索端点,我们也可以查看我们使用PagingAndSortingRepository创建的自定义端点:

{
  "_links": {
    "title-contains": {
      "href": "http://localhost:8080/books/search/title-contains{?query,page,size,sort}",
      "templated": true
    },
    "self": {
      "href": "http://localhost:8080/books/search"
    }
  }
}

The HAL above shows our title-contains endpoint displaying suitable search criteria. Note how the author-contains endpoint is missing since we defined that it should not be exported.

上面的HAL显示了我们的title-contains端点显示合适的搜索标准。注意author-contains端点是如何丢失的,因为我们定义它不应该被导出。

6.3. Viewing Embedded Resources

6.3.查看嵌入式资源

Embedded Resources show the details of the individual book records on our /books endpoint. Each resource also contains its own Properties and Links section:

嵌入资源显示了我们/books端点上的单个图书记录的细节。每个资源也包含自己的属性链接部分。

embed-2

6.4.  Using Forms

6.4. 使用表格

The question mark button in the GET column within the links section denotes that a form modal can be used to enter custom search criteria.

链接部分内GET栏中的问号按钮表示可以使用表单模态来输入自定义搜索标准。

Here is the form for our title-contains endpoint:

这里是我们的title-contains端点的表格。

The HAL browser selection form

Our custom URI returns the first page of 20 books where the title contains the word ‘Java’.

我们的自定义URI会返回标题包含 “Java “一词的20本书中的第一页

6.5. The Hal Inspector

6.5.哈尔检查员

The inspector makes up the right side of the browser and contains the Response Headers and Response Body. This HAL data is used to render the Links and Embedded Resources that we saw earlier in the tutorial.

检查器构成了浏览器的右侧,包含响应头和响应体。这些HAL数据用于渲染我们在本教程早期看到的链接和嵌入式资源

7. Conclusion

7.结语

In this article, we’ve summarised what HAL is, why it’s useful and why it can help us to create superior self-documenting REST APIs.

在这篇文章中,我们总结了什么是HAL,为什么它是有用的,以及为什么它可以帮助我们创建卓越的自文档化REST APIs.

We have built a simple REST API with Spring which implements the PagingAndSortingRepository, as well as defining our own endpoints. We’ve also seen how to exclude certain endpoints from the HAL browser.

我们用Spring构建了一个简单的REST API,实现了PagingAndSortingRepository,同时也定义了我们自己的端点。我们还看到了如何将某些端点从HAL浏览器中排除

After defining our API, we populated it with test data and explored it in detail with the help of the HAL browser. We saw how the HAL browser is structured, and the UI controls which allowed us to step through the API and explore its data.

在定义了我们的API之后,我们用测试数据填充了它,并在HAL浏览器的帮助下对其进行了详细的探索。我们看到了HAL浏览器的结构,以及允许我们通过API和探索其数据的UI控件。

As always, the code is available over on GitHub.

一如既往,代码可在GitHub上获得