Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i return 404 http status from dropwizard

Tags:

dropwizard

new to dropwizard! is there anyway that I can manually return different http status codes from the apis? basically something similar to this!

@GET
@Timed
public MyObject getMyObject(@QueryParam("id") Optional<String> id) {
    MyObj myObj = myDao.getMyObject(id)
    if (myObj == null) {
          //return status.NOT_FOUND; // or something similar 
          // or more probably 
          // getResponseObjectFromSomewhere.setStatus(mystatus)

    }

    return myObj;
}
like image 491
nightograph Avatar asked Mar 17 '15 21:03

nightograph


3 Answers

The simplest way is to return an Optional<MyObject>. Dropwizard will automatically throw a 404 when your result is Optional.absent() or Optional.empty() if you use the dropwizard-java8 bundle.

Just do:

@GET
@Timed
public Optional<MyObject> getMyObject(@QueryParam("id") Optional<String> id) {
    Optional<MyObject> myObjOptional = myDao.getMyObject(id)
    return myObjOptional;
}

Obviously you need to update your DAO according by returning Optional.fromNullable(get(id)) for Guava or Optional.ofNullable(get(id)) for Java8 bundle.

There is no need to play around with custom Response objects unless you want to return a custom status code outside of 200 and 404

like image 154
yunspace Avatar answered Nov 05 '22 21:11

yunspace


It's as simple as throwing a WebApplicationException.

@GET
@Timed
public MyObject getMyObject(@QueryParam("id") Optional<String> id) {
  MyObject myObj = myDao.getMyObject(id)
  if (myObj == null) {
    throw new WebApplicationException(404);
  }
  return myObj;
}

As you get further along you may want to put together custom exceptions which you can read more about here.

like image 40
condit Avatar answered Nov 05 '22 20:11

condit


I would recommend using the JAX-RS Response object instead of returning your actual domain object in the response. It serves as an excellent standard for including metadata with your response object and provides a nice builder for handling status codes, headers, customer content types, etc.

//import javax.ws.rs.core.Response above
@GET
@Timed
public Response getMyObject(@QueryParam("id") Optional<String> id) {
  MyObject myObj = myDao.getMyObject(id)
  if (myObj == null) {
    //you can also provide messaging or other metadata if it is useful
    return Response.status(Response.Status.NOT_FOUND).build()
  }
  return Response.ok(myObj).build();
}
like image 38
th3morg Avatar answered Nov 05 '22 21:11

th3morg