Skip to content

RESTful API Architecture

MasterLinux edited this page May 13, 2014 · 4 revisions

To implement new Resources you have to keep a specific architecture. Simplified it looks like

API <--> Service <--> DAO <--> DataSource

#API The API ist just the entry point for requests and provides the public interface.

@Path("/exampleResource")
public class Sessions extends BaseResource {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getResource(
            @BeanParam SomeBeanParam param
    ) {
        //calls the specific service of this resource
        return new ExampleResourceService(param.getParam1(), param.getParam2()).getResource();
    }
}

#Service A service is used to communicate with the specific resource DAO and building the response. In this example the following code snippet shows the usage of SecureService which checks for authorization.

public class SessionService extends SecureService {

    public SessionService(String username, String password) {
        super(username, password);
    }

    public SessionService(String token) {
        super(token);
    }

    public Response getSession() {
        SessionsModel sessions = new SessionsModel();
        Response.Status status = Response.Status.OK;

        if(missingCredentials()) {
            status = Response.Status.BAD_REQUEST;
        } else if (!isAuthorized()) {
            status = Response.Status.UNAUTHORIZED;
        } else {
            try {
                sessions = SessionsDAO.getInstance().getSessionByUserId(getUserId());
            } catch (ServiceUnavailableException | OperationException e) {
                status = Response.Status.INTERNAL_SERVER_ERROR;
            } catch (ResourceNotFoundException e) {
                status = Response.Status.NOT_FOUND;
            }
        }

        return sessions.toResponse(status);
    }
}

#DAO

Clone this wiki locally