14 Webサービス - Reference Documentation
Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith
Version: null
Translated by: T.Yamamoto, Japanese Grails Doc Translating Team.
【注意】このドキュメントの内容はスナップショットバージョンを元に*意訳*されているため、一部現行バージョンでは未対応の機能もあります。
14 Webサービス
Web services are all about providing a web API onto your web application and are typically implemented in either REST or SOAP
WebサービスはWebアプリケーションにWeb APIを提供するものであり、通常はSOAPまたはRESTで実装されています。
14.1 REST
REST is not really a technology in itself, but more an architectural pattern. REST is very simple and just involves using plain XML or JSON as a communication medium, combined with URL patterns that are "representational" of the underlying system, and HTTP methods such as GET, PUT, POST and DELETE.
RESTは本来SOAPのようなプロトコルではなく、アーキテクチャスタイルです。RESTは非常に単純です。簡素なXMLやJSONを通信媒体に用いて、基本的なシステムとGET、PUT、POSTおよびDELETEといったHTTPメソッドを「表現する」URLパターンを組み合わせています。Each HTTP method maps to an action type. For example GET for retrieving data, PUT for creating data, POST for updating and so on. In this sense REST fits quite well with CRUD.
それぞれのHTTPメソッドは異なるアクションにマップします。例えば、GETはデータ検索、PUTはデータ作成、POSTは更新などとマップします。このため、RESTはCRUDと非常によく適合します。URLパターン URL patterns
The first step to implementing REST with Grails is to provide RESTful URL mappings:
GrailsでRESTを実装する1つ目のやり方として、以下のようにRESTfulなURLマッピングを提供する方法があります。static mappings = { "/product/$id?"(resource:"product") }
This maps the URI
この例では、/product onto a ProductController. Each HTTP method such as GET, PUT, POST and DELETE map to unique actions within the controller as outlined by the table below:/productというURIをProductControllerに紐付けます。GET、PUT、POSTおよびDELETEといった各HTTPメソッドは、下表に示したようにコントローラ内の一意のアクションに紐付きます。| メソッド | アクション |
|---|---|
GET | show |
PUT | update |
POST | save |
DELETE | delete |
In addition, Grails provides automatic XML or JSON marshalling for you.
さらにGrailsではXMLまたJSONでの自動マーシャリングも提供しています。You can alter how HTTP methods are handled by using URL Mappings to map to HTTP methods:
HTTPメソッドをマップする仕組みを使用して、URLマッピングをHTTPメソッドにハンドルすることが可能です:"/product/$id"(controller: "product") { action = [GET: "show", PUT: "update", DELETE: "delete", POST: "save"] }
However, unlike the
ただし、この場合は、先のresource argument used previously, in this case Grails will not provide automatic XML or JSON marshalling unless you specify the parseRequest argument:resourceと違い、parseRequest変数をURLマッピングに指定しないと、XMLやJSONのマーシャリングを自動的には行いません:"/product/$id"(controller: "product", parseRequest: true) { action = [GET: "show", PUT: "update", DELETE: "delete", POST: "save"] }
HTTPメソッド HTTP Methods
In the previous section you saw how you can easily define URL mappings that map specific HTTP methods onto specific controller actions. Writing a REST client that then sends a specific HTTP method is then easy (example in Groovy's HTTPBuilder module):
前のセクションでは、特定のHTTPメソッドを特定のコントローラのアクションにマップするURLマッピングが、どれほど簡単に定義できるかを見ました。特定のHTTPメソッドを送信するRESTクライアントを作成するのも簡単です。(GroovyのHTTPBuilderモジュールの例):import groovyx.net.http.* import static groovyx.net.http.ContentType.JSONdef http = new HTTPBuilder("http://localhost:8080/amazon") http.request(Method.GET, JSON) { url.path = '/book/list' response.success = { resp, json -> for (book in json.books) { println book.title } } }
Issuing a request with a method other than
通常のブラウザからGET or POST from a regular browser is not possible without some help from Grails. When defining a form you can specify an alternative method such as DELETE:GETまたはPOST以外のメソッドの要求を発行するためには、Grailsの援助が必要となります。フォーム(form)を定義する時に、DELETEのような別のメソッドを指定できます。<g:form controller="book" method="DELETE"> .. </g:form>
Grails will send a hidden parameter called
Grailsは_method, which will be used as the request's HTTP method. Another alternative for changing the method for non-browser clients is to use the X-HTTP-Method-Override to specify the alternative method name._methodというhiddenパラメータを送信し、これをHTTPメソッドの要求として使用します。ブラウザ以外のクライアントでメソッドを変更するためには、X-HTTP-Method-Overrideを使用して代替メソッド名を指定します。XMLマーシャリング - 読み取り XML Marshalling - Reading
The controller can use Grails' XML marshalling support to implement the GET method:
GrailsのXMLマーシャリングの機能をコントローラで使用して、GETメソッドの実装できます。import grails.converters.XMLclass ProductController { def show() { if (params.id && Product.exists(params.id)) { def p = Product.findByName(params.id) render p as XML } else { def all = Product.list() render all as XML } } .. }
If there is an
この例では、検索した内容が存在した場合はそのid we search for the Product by name and return it, otherwise we return all Products. This way if we go to /products we get all products, otherwise if we go to /product/MacBook we only get a MacBook.Productを返し、無い場合は全てを返します。この方法で、/productにアクセスすると全リストが返り、/product/MacBook等指定して存在した場合は、そのProductを返します。XMLマーシャリング - 更新 XML Marshalling - Updating
To support updates such as
PUT and POST you can use the params object which Grails enhances with the ability to read an incoming XML packet. Given an incoming XML packet of:PUTおよびPOSTのような更新をサポートするには、Grailsのparamsオブジェクトを利用してXMLを読み取ることができます。次のようなXMLを受信したとします。<?xml version="1.0" encoding="ISO-8859-1"?> <product> <name>MacBook</name> <vendor id="12"> <name>Apple</name> </vender> </product>
you can read this XML packet using the same techniques described in the Data Binding section, using the params object:
このXMLを読み込むには、データバインディングの章に記述された内容と同じく、paramsオブジェクトから取得することができます:def save() {
def p = new Product(params.product) if (p.save()) {
render p as XML
}
else {
render p.errors
}
}In this example by indexing into the
この例では、params object using the product key we can automatically create and bind the XML using the Product constructor. An interesting aspect of the line:paramsオブジェクトからproductキーを使用して取得し、Productクラスのコンストラクタに渡すことで自動的にバインドします:def p = new Product(params.product)is that it requires no code changes to deal with a form submission that submits form data, or an XML request, or a JSON request.
興味深い点は、JSONリクエストまたはXMLリクエストの対応は、通常のフォーム送信の対応とそれほど変わりがないということです。If you require different responses to different clients (REST, HTML etc.) you can use content negotation異なったクライアント(REST、HTMLなど)に対する異なった応答が必要な場合は、コンテントネゴシエーションを使用することができます。
The
Product object is then saved and rendered as XML, otherwise an error message is produced using Grails' validation capabilities in the form:Productオブジェクトが保存され、XMLとして描写されます。問題が起きた場合は、Grailsのバリデーション機能によってエラーメッセージが返信されます。<error> <message>The property 'title' of class 'Person' must be specified</message> </error>
JAX-RSでのREST REST with JAX-RS
There also is a JAX-RS Plugin which can be used to build web services based on the Java API for RESTful Web Services (JSR 311: JAX-RS).
RESTful Webサービス用のJava APIをベースとしたRESTを、JAX-RSプラグイン構築することも可能です。 (JSR 311: JAX-RS)
14.2 SOAP
There are several plugins that add SOAP support to Grails depending on your preferred approach. For Contract First SOAP services there is a Spring WS plugin, whilst if you want to generate a SOAP API from Grails services there are several plugins that do this including:
GrailsにはSOAPのサポートを追加するプラグインがいくつかあります。コントラクトファーストのSOAP向けにはSpring WSプラグインがあり、GrailsサービスからSOAP APIを生成したいのであれば以下のようなプラグインがあります。- CXF プラグインは、CXF SOAPスタックを使用します。
- Axis2 プラグインは、Axis2 を使用します。
- Metro プラグインは、Metro フレームワークを使用します。(コントラクトファースト向けに使用することもできます。)
Most of the SOAP integrations integrate with Grails services via the
ほとんどのSOAP系プラグインはGrailsのサービスにexposes static property. This example is taken from the CXF plugin:exposeプロパティを定義することによって、SOAPを統合することが可能です。下記はCXFプラグインの例です:class BookService { static expose = ['cxf'] Book[] getBooks() {
Book.list() as Book[]
}
}The WSDL can then be accessed at the location:
WSDLには次のようなロケーションでアクセスすることができます。 http://127.0.0.1:8080/your_grails_app/services/book?wsdlhttp://127.0.0.1:8080/your_grails_app/services/book?wsdlFor more information on the CXF plugin refer to the documentation on the wiki.
CXFプラグインについてもっと知りたい方は、ドキュメントを参照しましょう。
14.3 RSSとAtom
No direct support is provided for RSS or Atom within Grails. You could construct RSS or ATOM feeds with the render method's XML capability. There is however a Feeds plugin available for Grails that provides a RSS and Atom builder using the popular ROME library. An example of its usage can be seen below:
RSSやAtomについては、Grailsへの直接的な機能は提供されていません。renderメソッドのXML機能を使用して、RSSやATOMのフィードを構築することができます。他に、ROME ライブラリを使用してRSSとAtomビルダを提供したFeedsプラグイン もあります。その使用例を以下に示します。def feed() {
render(feedType: "rss", feedVersion: "2.0") {
title = "My test feed"
link = "http://your.test.server/yourController/feed" for (article in Article.list()) {
entry(article.title) {
link = "http://your.test.server/article/${article.id}"
article.content // return the content
}
}
}
}
