Best practise when making post request in JAX-RS

jax-rs post request body
jax-rs post example
jax-rs get json request body
jax-rs client post example
jax-rs get request parameter
jax-rs best practices
jax-rs parameters
javax ws rs @path

I have seen some different conventions regarding the response status code, when making a post request using JAX-RS.

I have seen this:

  Response.ok(//content or object).build();

My initial thought would be that this is wrong, since status code 200, just means ok, which is a broad term, but since we have 'Posted', I think 201 would be better since it also returns the URI of the element inside the header

 Response.created(//content or object).build();

here is want i want to achieve:

  @POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response createUser(String content) throws CityNotFoundException
{
    ReceivedCreateUser receivedUser = gson.fromJson(content, ReceivedCreateUser.class);
    User createdUser = userFacade.createUser(receivedUser.name,
                                             receivedUser.email,
                                             receivedUser.password,
                                             receivedUser.city,
                                             receivedUser.gender,
                                             receivedUser.dateOfBirth);
    if(createdUser == null){
        throw new WebApplicationException(Response.Status.NOT_FOUND);
    }
    return Response.ok(gson.toJson(UserDTO.basic(createdUser))).build();

}

i want to add the entity to the response, but created only accepts the uri not entities.

Whether or not to return a 201 on a POST request depends greatly on the functionality behind it. If your end-point creates a new entity in the system then 201 would be the way to go, but POST is also often used to perform search request with large option sets. In this case a 200 or 204 would be desirable in case of results or no results.

But to return an entity with a POST and response 201 you could do something similar to this:

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response createUser(String content) throws CityNotFoundException
{
    ReceivedCreateUser receivedUser = gson.fromJson(content, ReceivedCreateUser.class);
    User createdUser = userFacade.createUser(receivedUser.name,
                                         receivedUser.email,
                                         receivedUser.password,
                                         receivedUser.city,
                                         receivedUser.gender,
                                         receivedUser.dateOfBirth);
    if(createdUser == null){
       throw new WebApplicationException(Response.Status.NOT_FOUND);
    }
    return Response
       .created(new Uri("http://example.org"))
       .entity(gson.toJson(UserDTO.basic(createdUser)))
       .build();
}

JAX-RS Tutorial, This tutorial presents an overview of the core JAX-RS concepts, important is a Java programming language API spec that provides support in creating web services Methods annotation with the @GET annotation respond to HTTP get requests. The @ApplicationPath Annotation Let's start at the top of the trees with the  The best practice is to always return a javax.ws.rs.core.Response. But note that even if you define the webresource with void , your server will return a HTTP response. On POST and PUT , it may be better to return the modified resource, including its id.

Response.ok() is not Ok all the time, it might show that the request was done but actually no resource was created. You might want to use Response.created or Response.accepted. As in this link , you can see that it all depends on the business logic of your backend.

Best practices for method types in JAX-RS, In practice, POST works well for creating resources. The URL of the newly created resource should be returned in the Location response header. We'll now look at some common best practices when writing JAX-RS client code. Category Education; Show more Advanced JAX-RS 17 - Making a POST request - Duration: 8:37. Java Brains 32,171

Response type is not the best return to clients and automatic documentation like Swagger, because it doesn't have too much information. I prefer particularly to return the entity directly how to bellow:

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public UserDTO createUser(String content) throws CityNotFoundException
{
    ReceivedCreateUser receivedUser = gson.fromJson(content, ReceivedCreateUser.class);
    User createdUser = userFacade.createUser(receivedUser.name,
                                         receivedUser.email,
                                         receivedUser.password,
                                         receivedUser.city,
                                         receivedUser.gender,
                                         receivedUser.dateOfBirth);
    if(createdUser == null){
       throw new WebApplicationException(Response.Status.NOT_FOUND);
    }

    return UserDTO.basic(createdUser);
}

This will return a Status Code = 200, but have many ways to change to 201. My favorite is overriding the javax.ws.rs.container.ContainerResponseFilter.filter(...) as bellow:

import static org.springframework.http.HttpMethod.POST;
import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.http.HttpStatus.OK;

import java.io.IOException;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;

@Provider
public class LocalContainerResponseFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
        throws IOException {
        if (POST.name().equals(requestContext.getMethod()) && OK.value() == responseContext.getStatus()) {
            responseContext.setStatus(CREATED.value());
        }
    }

}

This will change JAX-RS behavior returning 201 for all POST ok.

More 2 tips:

  1. you can change a parameter (String content) to (ReceivedCreateUser content); and

  2. you can put the code "throw new WebApplicationException" inside userFacade.createUser(...)

Advanced JAX-RS 16 - Some Best Practices, REST API Best Practices - With Design Examples from Java and Spring Web Services in the Java world, are Spring MVC, Spring REST and JAX-RS. Think about the HTTP request methods that you need to make use of. -Java API for RESTful Web Services (JAX-RS), is a set if APIs to developer REST service. -JAX-RS is part of the Java EE6, and make developers to develop REST web application easily. 1. JAX-RS Generalities 2. Java, REST and Jersey: 3.HelloWorld JAX-RS Web Service : 4.Utility of @Produces : 5.RestFul & JAXB :

REST API Best Practices, In this post, we will learn to create REST APIs using JAX-RS 2.0 (Java API for URI patterns and HTTP operations to individual methods of your Java class. @​POST, Annotated method will handle the HTTP POST requests on It helps in making web.xml file almost empty – with no REST specific configuration at all. JAX-RS is a JAVA based programming language API and specification to provide support for created RESTful Web Services. Its 2.0 version was released on the 24th May 2013. JAX-RS uses annotations available from Java SE 5 to simplify the development of JAVA based web services creation and deployment.

Create REST APIs with JAX-RS 2.0 – REST API Tutorial, REST API Best Practices — Design Examples From Java and Spring Web Services in the Java world, are Spring MVC, Spring REST and JAX-RS. Think about the HTTP request methods that you need to make use of. Advanced JAX-RS 16 - Some Best Practices by Java Brains. 6:04. Advanced JAX-RS 17 - Making a POST request by Java Brains. 8:37. Advanced JAX-RS 18 - Creating Invocations

REST API Best Practices, The data classes are awesome for writing POJOs. Use libraries. Rest-Assured to fluently create HTTP requests and assertions  Website: http://javabrains.koushik.org/courses In this tutorial, we'll implement the POST method API to create new instances of Message resource.

Comments
  • Then use 201 Created.
  • Yes, but then i can't give back the entity, that was created using the post method
  • The 201 response payload typically describes and links to the resource(s) created. (httpstatuses.com/201) What exactly do you want to do?
  • I will update the question, and add code,
  • Cant you do a Response.created(uri).entity(entity).build()?