Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a Jax-RS RESTful service that accepts both POST and GET?

I'm converting one of my existing service to become RESTful and I've got the basic things working with RestEasy. Some of my client apps should be able to execute both GET and POST requests to several services. I'm just seeking if there is any easy way around jax-rs to specify that API should accept both GETs and POSTs. Following you can find a test method, let me know if you see any way around without duplicating this in another class with @GET and @QueryParam.

@POST
@Path("/add")
public Response testREST(@FormParam("paraA") String paraA,
        @FormParam("paraB")  int paraB) {

    return Response.status(200)
            .entity("Test my input : " + paraA + ", age : " + paraB)
            .build();

}
like image 767
Charith De Silva Avatar asked Nov 15 '12 23:11

Charith De Silva


People also ask

Can we use same API for GET and POST?

But in general terms GET is used when server returns some data to the client and have not any impact on server whereas POST is used to create some resource on server. So generally it should not be same.

What annotation is to be used for the class which receives requests and responses for RESTful services?

The @GET annotation is a request method designator, along with @POST , @PUT , @DELETE , and @HEAD , defined by JAX-RS and corresponding to the similarly named HTTP methods. In the example, the annotated Java method will process HTTP GET requests.


1 Answers

Just put your method body in another method and declare a public method for each HTTP verb:

@Controller
@Path("/foo-controller")
public class MyController {

    @GET
    @Path("/thing")
    public Response getStuff() {
        return doStuff();
    }

    @POST
    @Path("/thing")
    public Response postStuff() {
        return doStuff();
    }

    private Response doStuff() {
        // Do the stuff...
        return Response.status(200)
                .entity("Done")
                .build();
    }
}
like image 178
blong Avatar answered Nov 03 '22 08:11

blong