New Tutorials:   NUMPY    TKINTER    KOTLIN    JAVASCRIPT    SASS/SCSS    PL/SQL    Matplotlib    C++ Programs

REST: Building a Generic Response

So far when we send a response to the client we have always send the status code as 200 in case of successful response but a good REST API design API sends different status code in response for different situations.

For example, we should send the status code of 201 in case of POST method, which broadcasts to the client that the resource has been successfully created.

public Response getAllStudents(@Context HttpHeaders headers)
	List<Student> students = studentService.getAllStudents();
	GenericEntity<List<Student>> entity = new GenericEntity<List<Student>>(students){};
	return Response.status(Status.OK).entity(entity).build();

The response class contains the HTTP line, HTTP headers and the HTTP message body.

public Response addStudent(Student student)
	String response = studentService.addStudent(student);
	return Response.status(Status.CREATED).entity(response).build();


So for the POST method the 201, Created status is sent. Hence, with the use of the Response class, more generic and informative response can be sent to the client.