23.4.5. Exposing entities via RESTful API

Seam makes it really easy to use a RESTful approach for accessing application data. One of the improvements that Seam introduces is the ability to expose parts of your SQL database for remote access via plain HTTP calls. For this purpose, the Seam/RESTEasy integration module provides two components: ResourceHome and ResourceQuery, which benefit from the API provided by the Seam Application Framework (Chapter 13, The Seam Application Framework). These components allow you to bind domain model entity classes to an HTTP API.

23.4.5.1. ResourceQuery

ResourceQuery exposes entity querying capabilities as a RESTful web service. By default, a simple underlying Query component, which returns a list of instances of a given entity class, is created automatically. Alternatively, the ResourceQuery component can be attached to an existing Query component in more sophisticated cases. The following example demonstrates how easily ResourceQuery can be configured:
<resteasy:resource-query
   path="/user"
   name="userResourceQuery"
   entity-class="com.example.User"/>
With this single XML element, a ResourceQuery component is set up. The configuration is straightforward:
  • The component will return a list of com.example.User instances.
  • The component will handle HTTP requests on the URI path /user.
  • The component will by default transform the data into XML or JSON (based on client's preference). The set of supported mime types can be altered by using the media-types attribute, for example:
<resteasy:resource-query
   path="/user"
   name="userResourceQuery"
   entity-class="com.example.User"
   media-types="application/fastinfoset"/>
Alternatively, if you do not like configuring components using XML, you can set up the component by extension:
@Name("userResourceQuery")
@Path("user")
public class UserResourceQuery extends ResourceQuery<User>
{
}
Queries are read-only operations, the resource only responds to GET requests. Furthermore, ResourceQuery allows clients of a web service to manipulate the resultset of a query using the following path parameters:
Parameter name Example Description
start /user?start=20 Returns a subset of a database query result starting with the 20th entry.
show /user?show=10 Returns a subset of the database query result limited to 10 entries.
For example, you can send an HTTP GET request to /user?start=30&show=10 to get a list of entries representing 10 rows starting with row 30.

Note

RESTEasy uses JAXB to marshall entities. Thus, in order to be able to transfer them over the wire, you need to annotate entity classes with @XMLRootElement. Consult the JAXB and RESTEasy documentation for more information.