Search code examples
javajax-rsjava-ee-5

Trying to build a REST-Service with encapsulated http response codes


I'm currently trying to build a REST webservice using Java/EE(5) that fully encapsulates the http responses, so every request should give back response code 200 (OK) and should look like this:

{   
    "msg" : { // imagine some datastructure here },
    "error" : {
        "code" : 200 // http response code
        "status" : "OK" // some string defining this
    }
}

My prefered framework is JAX-RS (we plan to migrate to EE6 soon, so migration is one of the topics while developing this), but can JAX-RS do this?


Solution

  • The easiest way to always return 200 OK and Content-Type: application/json with JAX-RS:

    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    import javax.ws.rs.core.Response;
    
    @Path("/not-rest")
    @Produces("application/json")
    public class NotRestBean {
    
        @GET
        public Response getSoapStyle() {
            String json = "{}"; // build your response here
            return Response.ok(json).build();
        }
    }
    

    Again, I don't recommend to do this. A central part of REST is the Uniform Interface which includes proper response codes.