Build a RESTful Webservice in less than 5 minutes

There are quite some tutorials around about building and exposing a RESTful Webservice, but some of them are outdated and make you wade through complex dependencies and tinkering with deployment descriptors and web.xml files. But using RESTeasy, the JBoss implementation that is fully compliant with the JAX-RS 2.0 JCP specification, and Eclipse you can build a simple webservice (“hello world”) with less than 10 lines of sourceode with annotations and no web.xml used in a few minutes and run it on Wildfly.

Lets build a webservice that creates random numbers.

Create at Dynamic Web Project

New Project

New Project

 

sdfsdf

Project Randomizer

 

Create 2 classes for application and resource

Abstract class application to declare the root resource and the resource class to define the exposed methods.

New class

New class

 

Application Class

Application Class

 

Resource Class

Resource Class

 

Build and Deploy to Wildfly

Run on Server

Run on Server

 

Call Webservice in browser

http://localhost:8080/DemoRandomizer/randomservice/random/number

Calling webservice

Calling webservice

This is the most simple webservice you could build. Certainly implemented in 5 minutes.


Now we could extend the webservice by adding versioning, securing with a API key, add parameters and respond in JSON or XML.

 

	@Path("/numberrange")
	@GET
	@Produces("application/json")
	public Response getRandom(@QueryParam("min") int min, @QueryParam("max") int max) {
		
		Random randomGenerator = new Random();
		int randomInt = randomGenerator.nextInt((max - min) + 1) + min;
		
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("minimum", min); 
		jsonObject.put("maximum", max); 
		jsonObject.put("value", randomInt); 
		
		return Response.status(200).entity(jsonObject.toString()).build();
	}

http://localhost:8080/DemoRandomizer/randomservice/random/numberrange?min=10&max=20

Call Webservice

Call Webservice (JSON Viewer extension for Chrome)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s