Menno
Menno

Reputation: 12641

Return value of RESTful Web Service, taking a null value into account

I am creating a client to my RESTful Web Service. In this case, my Server will not always return the expected object (e.g. nothing found on a given parameter, so return is NULL).

@GET
@Path("/person/{name}")
@Produces("application/xml")
public Person getPerson(@PathParam("name") String name) {
    return people.byName(name);
}

The byName() method will return NULL if the given name is not found. Upon unmarshalling the given object, this will raise an exception. What is the most common and clean way to just result in an if/else statement or something to handle the returns in different ways?

JAXBContext jcUnmarshaller = JAXBContext.newInstance(Person.class);
Unmarshaller unmarshaller = jcUnmarshaller.createUnmarshaller();
return (Person) unmarshaller.unmarshal(connection.getInputStream());

SOLUTION

getPerson( ) throws WebApplicationException { 
    throw new WebApplicationException(404);
}

Upvotes: 4

Views: 4970

Answers (2)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340933

The idiomatic way to handle such situations is to return 404 Not Found response code. With you can throw WebApplicationException:

@GET
@Path("/person/{name}")
@Produces("application/xml")
public Person getPerson(@PathParam("name") String name) {
    Person personOrNull = people.byName(name);
    if(personOrNull == null) {
      throw new WebApplicationException(404);
    }   
    return personOrNull;
} 

Upvotes: 8

dnc253
dnc253

Reputation: 40347

If you're looking for a pure REST service, you should return the HTTP response code 404 - Not Found when a person isn't found. So, it would look something like this:

public Person getPerson(@PathParam("name") String name) {
    Person person = people.byName(name);
    if (null != person) {
       return person
    }
    else {
       //return 404 response code (not sure how to do that with what you're using)
    }
}

Upvotes: 2

Related Questions