20100318

REST API in 15 Minutes, Or Your Money Back!

In keeping up with the times, we @ ACTGENT are exposing a REST API to our engine. We already have a pretty robust custom RPC framework in place (similar to Google's protobufs, but based on JSON with types added to the payload). Point is, we're already pretty well-positioned to expose a REST API.

When we got around to it, we found Jersey, a great JAX-RS implementation, which made the job even more trivial. Together with Jackson, a high-perf JSON serializer, we had our RPC services spit out JSON responses to REST requests within an hour.

Documentation, however, it a bit ... distributed. I hope putting down the steps for our particular set up (Tomcat) is helpful for others to get that hour of chasing documentation down to 15 minutes.

1. Get Jersey, Jackson, and dependencies into your classpath:

2. Update the WEB-INF/web.xml for the service for which you want to expose a REST API. Replace "com.actgent" below with your packages' root path, of course:

<servlet>
<servlet-name>api</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet
.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>org.codehaus.jackson.jaxrs;com.actgent</param-value>
</init-param>
...
</servlet>

<servlet-mapping>
<servlet-name>api</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>


3. Expose any class/method you want with annotations:

@Path("/TestRpcServer")
public class TestRpcServer {
...
@GET
@Path("user.json")
@Produces(MediaType.APPLICATION_JSON)
public User getSampleUser() {
User user = new User();
return user;
}
}


4. Access it!
  • Browse http://localhost:8080//TestRpcServer/getSampleUser

PS: Nods to