title: return newly generated id restful service post
body: <p>I'm trying to edit my create method in my REST webservice so it should return the newly created ID from the object. I've been trying for the past two days but I must be doing something terribly wrong...</p>
  
  <p>This is the edited create method on the server side:</p>
  
  <pre><code>@POST
  @Consumes({"application/xml", "application/json"})
  @Path("withID")
  @Produces("text/plain")
  public String create2(Users entity) {
      getEntityManager().persist(entity);
      getEntityManager().flush();
      System.out.println("new id: " + entity.getId());
      return String.valueOf(entity.getId());
  }
  </code></pre>
  
  <p>It is based on a (by netbeans) generated count() method as shown below:</p>
  
  <pre><code>@GET
  @Path("count")
  @Produces("text/plain")
  public String countREST() {
      return String.valueOf(super.count());
  }
  </code></pre>
  
  <p>If I do a request from my client to add a new Users object, it works like as expected. The new user is beeing added to the database. In the GlassFish server log, I see the newly created ID shown by the System.out.println command. However, if I do a test via the TestRestful Web Services in netbeans, paste the client generated XML code at the correct window and hit the TEST button, I receive a <strong>HTTP Status 415 - Unsupported Media Type</strong> error.</p>
  
  <p>I did some research and found <a href="https://stackoverflow.com/questions/797834/should-a-restful-put-operation-return-something">this</a> question. So my guess instead of returning a String, I should return a Response object with a 201 CREATED status and adjust the header or something? I checked out the spring example but as I am not using spring, I have no clue how to adjust the create2 method code... however I did a try but I'm missing some pieces:</p>
  
  <pre><code>@POST
  @Consumes({"application/xml", "application/json"})
  @Path("withID")
  @Produces("text/plain") //should this change to application/xml?
  public Response create2(Users entity) {
      getEntityManager().persist(entity);
      getEntityManager().flush();
      System.out.println("new id: " + entity.getId());
  
      //Response response = Response.created(... + "withID/" + entity.getId()); //response need an URI, can I get this through the entity object?
  
      return Response.status(200).entity(entity.getId().toString()).build();    
  }
  </code></pre>
  
  <p>I hope that I'm on the right track. Sorry for the long post, hope someone can help me out here. Thanks in advance!</p>
  
  <p><strong>Edit: working example now:</strong></p>
  
  <pre><code>@POST
  @Consumes({"application/xml"})
  @Path("withID")
  @Produces({"application/xml"})
  public Response create2(Users entity) {
      getEntityManager().persist(entity);
      getEntityManager().flush();
      return Response.status(201).entity(entity.getId().toString()).build();
  }
  </code></pre>