RESTful Service and DAO – Deciding on Responses

daodesignjavarestweb services

I am developing a RESTful API and I am using DAOs to serve data to the service.

I am having trouble deciding where certain responsibilities should fall, whether in the service or in the DAO contract. Or not just responsibilities but just deciding what each component should do or should not do.

In the scenario of the CRUD part of the API, let's focus in the create functionality, for example. When a resource is created (or not), what response is expected from the service? The serialized object that has been created? A true/false message? Nothing? This is what I mean:

// Option 1
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Resource createResource(Resource resource) {
    dao.create(resource);
    return resource;
}

// Option 2
@POST
@Consumes(MediaType.APPLICATION_JSON)
public void createResource(Resource resource) {
    dao.create(resource);
}

// Option 3
@POST
@Consumes(MediaType.APPLICATION_JSON)
public String createResource(Resource resource) {
    return dao.create(resource); // or even a custom message?
}

But going further. What should the DAO return? Should the dao.create() method return a boolean? Should it return the created object, or null if it couldn't be created? Or just be void?

// Option 1
public Resource create(Resource resource) {
    return resources.add(resource) ? resource : null;
}

// Option 2
public void create(Resource resource) {
    resources.add(resource);
}

// Option 3
public boolean create(Resource resource) {
    return resources.add(resource);
}

I just want to figure out what is usually expected from a RESTful service and then, decide what is the best division of "who should do what".

Or I am just overthinking this and any implementation makes sense and is as good as the other?

Best Answer

It's common for DAOs to return the newly-created resource, particularly when an ORM is used behind the scenes, for a couple of reasons I can think of:

  1. The returned object often has its surrogate primary key set, but more importantly -

  2. The returned object is often attached to the database session so further changes might automatically be committed when the session is closed.

In your example this isn't terribly important, but it's convenient when the more complex business logic is involved. None of the options you include follow this pattern.

As for REST endpoints, I agree with Eric, but I would add that on successful creation, respond with status code 201, the Location header set to the canonical URL of the new resource, and the serialized resource itself in the response body. Your Option 1 comes closest to this.