Skip to content

RESTful Web Applications

Estimated time to read: 3 minutes

REST Architecture

REST is a set of guidelines that developers adhere to when designing API's.

There are four principles that API's follow, these are:

  • Data and functionality are considered resources
    • These are identified through a URI
  • Resources are manipulated through a fixed set of operations
    • GET - Used for retrieving a resource
    • POST - Used for creating a resource
    • PUT - Used for updating a resource
    • DELETE - Used for deleting a resource
  • Resources can be represented in multiple formats
    • Such as HTML, XML, Plain Text et al
  • Communication between the client and endpoint is stateless
    • The server will not save any information about the client that made the call

RESTful Web Applications

RESTful API's are easier to create and consume when compared to a technology such as SOAP. API's are used for web integration and mobile device applications.

REST API's can be built using Spring Boot.

The @RestController annotation can be used on methods within the controller layer to return data directly to the HTTP response as JSON, this is in place of the @Controller annotation. @RestController is used in tandem with the @RequestMapping annotation which maps HTTP requests to the correct handler methods, in this instance GET.

Note

The @ResponseBody annotation indicates to Spring that the return value of the method is seralized directly to the body of the HTTP request. This is fine for API's but may not be the expected behavior in other use cases.

Note

The @ResponseBody annotation includes the entire HTTP response. Status code, Headers and Response Body are all included.

RestExample.java
// ...

@RestController // The @RestController annotation replaces the @Controller annotation. @RestController implements @Controller and @ResponseBody annotations
@RequestMapping("/tza")
public class TzaController {
    // ...
}

// ...

@GetMapping("/tickets")  // The @GetMapping annotation specifically handles GET requests, in this instance, GET requests for /tickets
public ResponseEntity<List<Ticket>> getAllTickets(){
    // ... 
}

@GetMapping("/applications")
public ResponseEntity<List<Application>> getAllApplications() {
    List<Application> list = applicationService.listApplications();
    return new ResponseEntity<List<Application>>(list, HttpStatus.OK); // The endpoint can declare the HTTP status code
}

Testing with cURL

cURL can be used to call URL's and view the response.

cURL is built in to many operating systems' and can be accessed via the following command:

curl <ip/site_address>:<port>/<path>

Response Formats

ResponseEntity is a generic type, as a result, any type can be used as the response body.

Class ResponseEntity<T>

return new ResponseEntity<List<TYPE>>(list, HttpStatus.OK);

Response Codes

There are several status codes that can be returned. A status code is issued by the server in a response to a client's request.

All HTTP response status codes are separated into five classes or categories. The first digit of the status code defines the class of response, while the last two digits do not have any classifying or categorization role. There are five classes defined by the standard:

  • 1xx informational response – the request was received, continuing process
  • 2xx successful – the request was successfully received, understood, and accepted
  • 3xx redirection – further action needs to be taken in order to complete the request
  • 4xx client error – the request contains bad syntax or cannot be fulfilled
  • 5xx server error – the server failed to fulfil an apparently valid request

For more detail, see Mozilla: HTTP Response Status Codes

Exception Handling

Spring can indicate success or failure to a client by responding with the relevant HTTP status code in the response to the client.

ResponseStatusException is a programmatic alterantive to the @ResponseStatus annotation and is the base class for exceptions used for applying a status code to a HTTP response.

An instance of ResponseStatusException can be created by providing HttpStatus, reason, cause as a return value.

By default, Spring Boot provides a default exception mapping that returns a JSON response with the HttpStatus code and an exception message.

Exceptions can be thrown as such:

// ...

@GetMapping("/application/id")
public ResponseEntity<Application> getApplication(@PathVariable("id") long id) {
    try {
        return new ResponseEntity<Application>(applicationService.findApplication(id)), HttpStatus.OK);
    } catch (ApplicationNotFoundException exception) {
        throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Application Not Found");
    }
}