Build RESTful Web Services

REST is an end point to transfer data using XML or JSON. There are several advantages about REST Web Services you may want to look into.
To build RESTful Web Services, there are 4 major specifications to make:

  1. Path
  2. Media type
  3. Method type
  4. Path Parameter Injection
In addition, because REST takes paths mainly as parameters, it’s possible to nest paths from one to another.

1. Path

To make the service accessible, you need to give it an application path and sub paths. The application path can be specified in web.xml or through annotation:

web.xml

<servlet-mapping>
    <servlet-name>javax.ws.rs.core.Application</servlet-name>
    <url-pattern>/mainpath/*</url-pattern>
</servlet-mapping>

Annotation

@javax.ws.rs.ApplicationPath("mainpath")
public class MyStoreApplication extends javax.ws.rs.core.Application {
    /* empty class body */
}
For sub paths, @Path is placed on the class level. E.g. to reach the following class with above settings, the URL is http://<domain&gt;:<port>/<application_name>/mainpath/subpath
@Path("subpath")
public class Service{}

It is possible to put @Path on method level, and this will be talked in the following sections.

2. Media Type

There are mainly 2 types data that REST can produce or consume: XML and JSON. In particular, @Produces indicates the methods to send out responses with the XML or JSON data, whereas, @Consumes is for methods receiving XML or JSON data attached with requests. When they are annotated on the class level, it means the same as to annotate on every method within the class.

@Path("subpath")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class Service{}

3. Method Type

Obviously, the RESTful Web Services should respond to different request accordingly. In order to do that, you can use @GET @POST @PUT @DELETE annotations on the methods to map with CRUD operations against database.

@Path("subpath")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class Service{
    @GET
    public Response findById(String id){
        // ett can be a JSON String or the Entity object(s)
        return Response.status(Status.OK).entity(ett).build();
    }
}

4. Path Parameter Injection

In order to get the path parameter, which is a portion of the URL, @Path and @PathParam is used as following:

@Path("subpath")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class Service{
    @EJB
    EntityEJB entityEJB;

    @GET
    @Path("{id}")
    public Response findById(@PathParam("id") String id){
        Entity ett = entityEJB.findById(id);
        return Response.status(Status.OK).entity(ett).build();
    }
}

In the above code, the braces surrounding id in @Path annotation indicates that id is a place holder in the URL. id in @PathParam means the value of this portion of URL is injected into the String id. For example, if the URL is .../subpath/a1-5, the value of String id will be “a1-5“.
In addition, the JSON object attached with the request can also be injected implicitly. Here is an example:

@PUT
public Object create(Entity ett) {
    return entityEJB.persist(ett);
}

Topic: nested path

There are cases you may want to organize methods of a Service in several classes. Check this code about Service and SubService to find more.

This blog may not be up to date. Please see the original post from Blogger http://ift.tt/2eM5T4K
via IFTTT.

Advertisements

Send HTTP Request

When testing RESTful Web Services, you can’t just enter a URL in browser since that can only send a GET request. In order to conduct other request types, one way you can do is to use a ClientBuilder.

There are 3 steps to send a request using ClientBuilder:
  1. Create an Entity; (javax.ws.rs.client.Entity)
  2. Configure an Invocation$Builder;
  3. Use Invocation$Builder to send a request attached with the Entity.

Prerequisite

Because ClientBuilder itself is defined in javax.ws.rs.client, it needs a JavaEE container, or at least, the RESTEasy JAX-RS API, which I like to recommend.

Step 1. Create an Entity

The Entity creating here is mainly considered as a JSON or XML object wrapped by the Entity class, although you have many options. The following code shows how an Entity is conducted:

// Conduct an entity using content, which is an JSON String
Entity<String> entity = Entity.entity(content, MediaType.APPLICATION_JSON);

You can notice that the content is not necessarily to be a String, and the generic type of the entity is going to change accordingly.

Step 2. Configure an Invocation$Builder

To configure an Invocation$Builder, use ClientBuilder.newClient() to create a new Client object, configure the Client object, and build the Invocation$Builder:

  1. Create a new Client object;
  2. Configure the Client object;
  3. Build the Invocation$Builder.
// Create a new Client object
Client client = ClientBuilder.newClient();

// Set an authentication (if needed)
client = client.register(new BasicAuthentication(username, password));

// Set the url, which can be a String or wrapped object
WebTarget target = client.target(url);

// Build a builder
Builder builder = target.request();

Step 3. Use Invocation$Builder to send a request attached with the Entity.

Depending on what method you want to invoke on the server side, you can do GET, POST, PUT, DELETE, which generally are mapped to CRUD operations on the server side:

// To attach anything with GET method, modify the url
Response response = builder.get();

Response response = builder.post(entity);

Response response = builder.put(entity);

Response response = builder.delete(entity);

See another example of using the ClientBuilder in a demo project.

This blog may not be up to date. Please see the original post from Blogger http://ift.tt/2eyHNu7
via IFTTT.