【Spring MVC】REST APIにて基本的なGET通信を行う方法

概要

REST APIアプリを作成し、GET通信を行う方法についてまとめた。

 

事前準備

クライアントとJSON形式で疎通するためのリソースクラスと、リソースクラスを処理するサービスクラスを用意する。
※以下の記事の続きとなる。

あわせて読みたい

概要 これから数回にかけてREST APIについて学んだことを載せていく。 今回はREST APIの仕組みとプロジェクト作成方法について紹介する。 尚、RESTとは何かということについては取り扱わない。   仕組み[…]

 

リソースクラス

以下のResourceクラスでクライアントとやりとりを行う。

 

Resource.java


package com.example.restprototype.web.resources;

import java.time.LocalDate;

import com.fasterxml.jackson.annotation.JsonFormat;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

/**
 * REST APIにて返却するリソースオブジェクト
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Resource {
	/** ID */
	private String id;
	/** 名前 */
	private String name;
	/** とある日付 */
	@JsonFormat(pattern = "yyyy-MM-dd")
	private LocalDate hogeDate;
}

 

サービスクラス

ビジネスロジックを扱うクラス。
このサービスクラスを呼び出し、キーに紐づくリソースの取得を行う。

尚、REST APIの動きに焦点をあてるため、DBやDAOクラスなどは用意しない。
また、本来はクライアントと疎通するリソースクラスと、サービスが扱うリソースクラスは分けるべきだが、ここでは気にしない。

 

ResourceService.java


package com.example.rest_prototype.biz.service;

import java.time.LocalDate;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.stereotype.Service;

import com.example.restprototype.web.resources.Resource;

@Service
public class ResourceService {

	/** DBの代わりに仮実装 */
	private static Map<String, Resource> tmpDbMap = new ConcurrentHashMap<>();

	/**
	 * 初期化(仮想DB)
	 */
	static {
		var dto1 = new Resource("1", "りんご", LocalDate.of(2025, 2, 1));
		var dto2 = new Resource("2", "ごりら", LocalDate.of(2024, 6, 5));
		var dto3 = new Resource("3", "らっぱ", LocalDate.of(2023, 5, 10));

		// 初期化
		tmpDbMap.put(dto1.getId(), dto1);
		tmpDbMap.put(dto2.getId(), dto2);
		tmpDbMap.put(dto3.getId(), dto3);
	}

	/**
	 * IDに紐づくリソースを取得
	 * @param id
	 * @return
	 */
	public Resource find(String id) {
		return tmpDbMap.get(id);
	}
}

 

Bean登録

ルートアプリケーションコンテキストのコンポーネントスキャンを有効にする。
これにより、@ServiceアノテーションがついたコンポーネントがDIコンテナで管理される。

 

applicationContext.xml


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
         http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
         		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.1.xsd">

	<!-- コンポーネントスキャン -->
	<context:component-scan base-package="com.example.rest_prototype.biz" />
</beans>

 

基本的なGET通信

GETリクエストに紐づくハンドラメソッドをコントローラーに作成し、REST API クライアントから動作確認を行う。

 

コントローラー

URIにパスパラメータを設定し、パラメータに該当するリソースを返却する。

 

Rest01Controller.java


package com.example.rest_prototype.web.controller.rest01;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.rest_prototype.biz.service.ResourceService;
import com.example.restprototype.web.resources.Resource;

@Controller
public class Rest01Controller {
	/** ビジネスロジック */
	@Autowired
	private ResourceService service;

	/**
	 * パスパラメータに対応したリソースを返却する
	 * @param id
	 * @return
	 */
	@GetMapping(value = "rest01/{id}")
	@ResponseBody
	public Resource get(@PathVariable String id) {
		// IDをキーにリソース取得
		var res = service.find(id);

		return res;
	}

}

 

@GetMapping(value = “rest01/{id}”)

GETリクエストを受け付けるアノテーション。
「id」という名前の変数で、パスパラメータを取得するURLテンプレートをvalueに指定している。

あわせて読みたい

概要 Spring MVCにてクライアント側からGETまたはPOSTリクエストを行ってパラメータを取得する方法についてまとめた。   前提 Mavenプロジェクトの作成方法と基本的な画面疎通については以下を参照。 […]

【Spring MVC】基本的なGET/POSTリクエストの方法

 

@ResponseBody

メソッドの戻り値を、レスポンスに直接設定可能にするアノテーション。
Resourceオブジェクトを返却することで、
SpringのメッセージコンバーターがオブジェクトをJSON形式に変換して 、クライアント側にJSON情報が返却される

※実際に動作するメッセージコンバーターは、JavaBeansとJSONを相互変換を担うMappingJackson2HttpMessageConverterとなる

 

動作確認

サーバーを起動して、Talend API Testerを使用して動作確認を行う。
Talend API Testerの使用方法については以下を参照。

あわせて読みたい

概要 GUIのツールを使用してシンプルにREAT APIアプリにリクエストを送りたいと思い、Talend API Testerを使用してみた。 いろいろと便利だったため、基本的な使用方法について簡単にまとめた。   事[…]

Talend API Testerを使用してREST APIにリクエストする方法

 

GETリクエスト送信

GETリクエストを送信し、指定したIDに紐づくリソースオブジェクトがJSON形式になって返却された。

 

【Spring MVC】REST APIにて基本的なGET通信を行う方法_疎通成功
▲JSON形式でレスポンスを取得

 

まとめ

 

☑ リクエストハンドラに@ResponseBodyを指定することで、レスポンスボディに直接オブジェクトを設定できる

☑ メッセージコンバーターが動作してJavaBeansをJSON 形式に変換してくれる

☑ MappingJackson2HttpMessageConverterがJavaBeansとJSONの相互変換を担う

 

スポンサーリンク