Milindu Sanoj Kumarage
Milindu Sanoj Kumarage

Reputation: 2774

RESTful service with JAX-RS Create method responce

I'm developing a RESTful service using Java EE Jax-RS. I got my basic codes forward engineered with Netbeans.

The return type of create method in AbstractFacade which all my Resource Facades inherits is void.

public void create(T entity) {
        getEntityManager().persist(entity);
    }

This is my ComplainFacadeREST

@POST
@Consumes({"application/xml", "application/json"})
public void  create( Complain entity ) {
    super.create(entity);
}

Therefore it does not send any useful response once a resource is created. Instead I get a 204 No Content response. But this is not how it should happen, right?

If a resource has been created on the origin server, the response SHOULD be 201 (Created) and contain an entity which describes the status of the request and refers to the new resource, and a Location header

What should I do now? Getting no response seems a problem, I have to redirect the user to #/resource/:id in my AngularJS UI. For that, either I have to send the id of the newly created resource or send a correct Location header. May I change the AbstractFacade? Or is there any other way? Or have I missed something? People who have created AbstractFacade in Netbeans has marked create method as void for a good reason?

Upvotes: 1

Views: 338

Answers (2)

Kevin Rave
Kevin Rave

Reputation: 14426

If you want to return 201, why not add an abstraction around the create() method? Add a new layer in between and return 201 from that layer/class.

Upvotes: 1

John Ament
John Ament

Reputation: 11723

You should return a response object, e.g.

URI uri = uriInfo.getBaseUriBuilder().build(entity.getId());
return Response.created(uri).build();

Upvotes: 1

Related Questions