1. 概要

この記事では、 Spring Data REST の基本を説明し、それを使用して単純なRESTAPIを構築する方法を示します。

一般に、Spring DataRESTはSpringDataプロジェクトの上に構築されており、SpringDataリポジトリに接続するハイパーメディア駆動型RESTWebサービスを簡単に構築できます。すべてHALを駆動ハイパーメディアタイプとして使用します。

これにより、通常このようなタスクに関連する多くの手作業が不要になり、Webアプリケーションの基本的なCRUD機能の実装が非常に簡単になります。

2. Mavenの依存関係

単純なアプリケーションには、次のMaven依存関係が必要です。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId
    <artifactId>spring-boot-starter-data-rest</artifactId></dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
</dependency>

この例ではSpringBootを使用することにしましたが、従来のSpringでも問題なく動作します。 また、余分なセットアップを回避するためにH2組み込みデータベースを使用することを選択しましたが、この例はどのデータベースにも適用できます。

3. アプリケーションの作成

まず、Webサイトのユーザーを表すドメインオブジェクトを記述します。

@Entity
public class WebsiteUser {

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

    private String name;
    private String email;

    // standard getters and setters
}

すべてのユーザーには、名前と電子メール、および自動生成されたIDがあります。 これで、簡単なリポジトリを作成できます。

@RepositoryRestResource(collectionResourceRel = "users", path = "users")
public interface UserRepository extends PagingAndSortingRepository<WebsiteUser, Long> {
    List<WebsiteUser> findByName(@Param("name") String name);
}

これは、WebsiteUserオブジェクトを使用してさまざまな操作を実行できるようにするインターフェースです。 また、指定された名前に基づいてユーザーのリストを提供するカスタムクエリを定義しました。

@RepositoryRestResource アノテーションはオプションであり、RESTエンドポイントをカスタマイズするために使用されます。 これを省略することにした場合、Springは「 /users」ではなく「/websiteUsers」にエンドポイントを自動的に作成します。

最後に、アプリケーションを初期化するための標準の SpringBootメインクラスを記述します

@SpringBootApplication
public class SpringDataRestApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringDataRestApplication.class, args);
    }
}

それでおしまい! これで、完全に機能するRESTAPIができました。 実際の動作を見てみましょう。

4. RESTAPIへのアクセス

アプリケーションを実行し、ブラウザーで http:// localhost:8080 / に移動すると、次のJSONを受け取ります。

{
  "_links" : {
    "users" : {
      "href" : "http://localhost:8080/users{?page,size,sort}",
      "templated" : true
    },
    "profile" : {
      "href" : "http://localhost:8080/profile"
    }
  }
}

ご覧のとおり、「 / users 」エンドポイントが利用可能であり、すでに「?page 」、「?size 」、「[ X128X]?sort」オプション。

アプリケーションメタデータを提供する標準の「/profile」エンドポイントもあります。 応答は、RESTアーキテクチャスタイルの制約に従う方法で構造化されていることに注意することが重要です。 具体的には、統一されたインターフェイスとわかりやすいメッセージを提供します。 これは、各メッセージに、メッセージの処理方法を説明するのに十分な情報が含まれていることを意味します。

アプリケーションにはまだユーザーがいないため、 http:// localhost:8080 / users に移動すると、ユーザーの空のリストが表示されます。 curlを使用してユーザーを追加しましょう。

$ curl -i -X POST -H "Content-Type:application/json" -d '{  "name" : "Test", \ 
"email" : "[email protected]" }' http://localhost:8080/users
{
  "name" : "test",
  "email" : "[email protected]",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/users/1"
    },
    "websiteUser" : {
      "href" : "http://localhost:8080/users/1"
    }
  }
}

応答ヘッダーも見てみましょう。

HTTP/1.1 201 Created
Server: Apache-Coyote/1.1
Location: http://localhost:8080/users/1
Content-Type: application/hal+json;charset=UTF-8
Transfer-Encoding: chunked

返されるコンテンツタイプは「application/ hal +json」であることがわかります。 HAL は、API内のリソース間のハイパーリンクに一貫性のある簡単な方法を提供するシンプルな形式です。 ヘッダーには、 Location headerも自動的に含まれます。これは、新しく作成されたユーザーにアクセスするために使用できるアドレスです。

これで、 http:// localhost:8080 / users /1でこのユーザーにアクセスできます。

{
  "name" : "test",
  "email" : "[email protected]",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/users/1"
    },
    "websiteUser" : {
      "href" : "http://localhost:8080/users/1"
    }
  }
}

curlまたはその他のRESTクライアントを使用して、PUT、PATCH、およびDELETE要求を発行することもできます。 SpringDataRESTは自動的にHATEOASの原則に従うことに注意することも重要です。 HATEOAS はRESTアーキテクチャスタイルの制約の1つであり、APIを介して道を見つけるためにハイパーテキストを使用する必要があることを意味します。

最後に、前に作成したカスタムクエリにアクセスして、「test」という名前のすべてのユーザーを見つけてみましょう。 これは、 http:// localhost:8080 / users / search / findByName?name =testに移動することで実行されます。

{
  "_embedded" : {
    "users" : [ {
      "name" : "test",
      "email" : "[email protected]",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/users/1"
        },
        "websiteUser" : {
          "href" : "http://localhost:8080/users/1"
        }
      }
    } ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/users/search/findByName?name=test"
    }
  }
}

5. 結論

このチュートリアルでは、SpringDataRESTを使用して単純なRESTAPIを作成するための基本を示しました。 この記事で使用されている例は、リンクされているGitHubプロジェクトにあります。