Until now I have been doing my API's something like this:
@GET
@GZIP
@Path("/login")
@Produces(MediaType.TEXT_HTML)
public Response login(@QueryParam("email") String email, @QueryParam("password") String password){
UserDao userDao = new UserDao();
String token = userDao.getLogin(email, password);
if(token != null)
return Response.status(200).entity(token).build();
return Response.status(400).build();
}
And it works perfectly fine because in the client I just call the http service and it returns the token a string response or a json response.
But I did some research on other API's and I saw that their format is a little more complex than just a string/json response.
So I am trying to build some more serious structure I created an object for the response like this:
public class JsonResponse {
private String success;
private String error;
private Object data;
public JsonResponse(){
}
public JsonResponse(String success, String error, Object data) {
this.success = success;
this.error = error;
this.data = data;
}
//GETTERS/SETTERS...
}
So I changed the REST part from that one above to this:
@GET
@GZIP
@Path("/login")
@Consumes(MediaType.TEXT_HTML)
@Produces(MediaType.APPLICATION_JSON)
public Response login(@QueryParam("email") String email, @QueryParam("password") String password){
UserDao userDao = new UserDao();
JsonResponse jsonResponse = userDao.login(email, password);
if(jsonResponse.getSuccess() != null)
return Response.status(200).entity(jsonResponse).build();
return Response.status(400).entity(jsonResponse).build();
}
This way what I can do in the client is obtain the response instead of just the token string I get it like this:
{
success: "success",
error: null,
data: "$2a$10$nT0vSwBCDiRl1Xvfrqrh1un8Iu/w3OInjp.JQDKux1aA6YZoyfEt2"
}
or
{
success: null,
error: "An error occured because of '...specific problem from api...'",
data: "$2a$10$nT0vSwBCDiRl1Xvfrqrh1un8Iu/w3OInjp.JQDKux1aA6YZoyfEt2"
}
So my problem is the following: When the api send STATUS_CODE 200 I can indeed use that JSON
But when it returns STATUS_CODE 400 I can't get the error message from the json because the json is not sent
Do I need to use always STATUS_CODE 200 if I want to do the API like that? What are the best practice?