Spring Data RESTの紹介
データ]
-
リンク:/tag/spring-data-rest/[春のデータREST]
1概要
この記事ではhttp://projects.spring.io/spring-data-rest/[Spring Data REST]の基本を説明し、それを使って簡単なREST APIを構築する方法を説明します。
一般に、Spring Data RESTはSpring Dataプロジェクトの上に構築されており、Spring Dataリポジトリに接続するハイパーメディア駆動のREST Webサービスを構築することを容易にします。
それは通常そのようなタスクに関連した手作業の多くを取り除き、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>
この例ではSpring Bootを使用することにしましたが、従来の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
」にエンドポイントを作成します。
最後に、アプリケーションを初期化するための標準のSpring Bootメインクラスを作成します。
@SpringBootApplication
public class SpringDataRestApplication {
public static void main(String[]args) {
SpringApplication.run(SpringDataRestApplication.class, args);
}
}
それでおしまい!我々は今、完全に機能的なREST APIを持っています。実際に見てみましょう。
4 REST APIへのアクセス
アプリケーションを実行してブラウザで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
」、および「
?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
“であることがわかります。
http://stateless.co/hal
specification.html[HAL]は、API内のリソース間のハイパーリンクへの一貫した簡単な方法を提供する単純な形式です。ヘッダーには自動的に
Location__ヘッダーも含まれています。これは、新しく作成されたユーザーにアクセスするために使用できるアドレスです。
これで、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"
}
}
}
PUT、PATCH、およびDELETE要求を発行するためにcurlまたは他のRESTクライアントを使用することもできます。 Spring Data RESTは自動的に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結論
このチュートリアルでは、Spring Data RESTを使った簡単なREST APIの作成の基本を説明しました。この記事で使用されている例は、リンクされたhttps://github.com/eugenp/tutorials/tree/master/spring-data-rest[GitHubプロジェクト]にあります。