Saturday, January 6, 2018

REST tutorial : validations

Greetings!

Our API is all good but it currently accepts empty Todos. Let's fix that with validations.

You can find the complete source code here Todoapp

Hibernate Validator

Hibernate Validator allows to express and validate application constraints.
Implements JSR 380 bean validation api.
Hibernate validator is entirely separate from the persistence aspects of Hibernate.
http://hibernate.org/validator/

Hibernate Validator 6.0 is the Reference Implementation of the Bean Validation 2.0 specification.

Steps:

  • Update gradle
  • compile('javax.validation:validation-api:2.0.1.Final')
    compile('org.hibernate:hibernate-validator:6.0.7.Final')
  • Update controller method to add @Valid check
  • Update TodoDto with validators
  • Catch validation exception in global exception handler (MethodArgumentNotValidException)

Useful annotations

@Length(min=, max=) - check if the string length match the range
@Max(value=) - check if the value is less than or equals to max
@Min(value=) - check if the value is less than or equals to min
@NotNull(value=) - check if the value is not null
@NotEmpty - check if the string is not null nor empty
@Past - check if the date is in the past
@Future - check if the date is in the future
@Email - check whether the string is valid email address
@Size(min=, max=) - check if the element size is between min and max (included)
@AssertTrue, @AssertFalse - true, false
@Positive -  check if the value is positive
@Negative - check if the value is negative


With that, we have completed section 2 of our REST API.



REST tutorial : error handling

Greetings!

So far we have neglected error scenarios in our API. Any application without proper error handling is a disaster.

You can find the complete source code here Todoapp

Try these URLs and see the output.
http://localhost:8080/todoss
http://localhost:8080/todos/abcd

Spring has handled errors for us!! but the messages are not interesting enough.

Global exception handling

  • With Spring's @ControllerAdvice we can handle exception globally. 
  • ResponseEntityExceptionHandler : A convenient base class for @ControllerAdvice classes that wish to provide centralized exception handling across all @RequestMapping methods through @ExceptionHandler methods. 
  • @RestControllerAdvice is a new feature of Spring Framework 4.3, an annotation with combined @ControllerAdvice + @ResponseBody
  • Enable spring.mvc.throw-exception-if-no-handler-found to customize 404 error

Note that our TodoService is also updated to throw a custom exception.
See the complete code in error-handling branch.

In next part of the tutorial we are going to add validation to Todo itself.

Thursday, January 4, 2018

REST tutorial : Controller layer

Greetings!

This is the last post of our RESTful webservice section 1 ;) . Previous part is here
We still have to implement error handling, security etc

You can find the complete source code here Todoapp

Step 1: Create TodoController annotated with @RestController


Step 2: Implement our methods. Spring will do the REST ;)


Let's test our service using Postman.
start the server, gradle clean bootrun

Test 1: Empty Todos
Note the status: since we do not have any Todos yet, it is 404



Test 2: Create a Todo
We get the 201 status and created Todo's location in header



Test 3: List Todos



Test 4: Update a Todo



Test 5: Delete a Todo




That is all for now, though it is working we are yet to handle errors properly and secure our end points.

REST tutorial : Create service layer

Greetings!

Welcome to 3rd part of our tutorial series. Previous part is here

Let's quickly build our service.

You can find the complete source code here Todoapp

Step 1: Create DTO


Step 2: Update model to create from/ to DTO


Step 3: Define service interface


Step 4: Implement services


That is all for our services.

REST tutorial : Create repository

Greetings!

This is the 2nd post of our tutorial series. Previous part is here
In this part let's create our domain quickly.

You can find the complete source code here Todoapp

Spring Data JPA

Spring Data JPA improves the implementation of data access layers by reducing boilerplate codes. For the repository interfaces Spring provides the implementation automatically.
Lombok reduces boilerplate code for model objects. It can generate getter, setter, toString, hashCode, equals, constructors for you.
https://projectlombok.org

To make it simple, we will have Todo with Id, title and summary.

Step 1: Modify database properties


Step 2: Create Todo model


NOTE: Lombok will eliminate getter, setter, toString, hashCode burden.

Step 3 : Create Todo repository


With magic of Spring that is all ;)

Tuesday, January 2, 2018

REST tutorial introduction

Greetings!

In this tutorial series, we are going to study RESTful services with Spring.

We are going to build a TodoApp in this series since it is one of the easiest way to touch the technical stack.

You can find the complete source code here Todoapp

For the simplicity i'm going split tutorial into smaller parts.
  1. Section 1: CRUD
  2. Section 2: Error handling
  3. Section 3: Security
  4. Section 4: User interface
  5. Section 5 : Miscellaneous

Goal

  • Create a RESTful service using Java tech stack.

What you need

  • Java 8
  • Gradle 4
  • IDE

REST

REST stands for REpresentational State Transfer. It is an architectural style rather than a strict protocol. Not a standard but a set of constraints, such as being stateless, having a client/server relationship, and a uniform interface.

Spring Framework

The Spring Framework is an application framework and inversion of control container for the Java platform.

Spring Boot

Spring boot is a Spring based production-ready project initializer which create Spring-powered, production-grade applications and services with absolute minimum fuss.

HTTP methods

HTTP VerbCRUD
GETRead
POSTCreate
PUTUpdate
DELETEDelete

HTTP Status Codes

HTTP codeStatus
200OK
201Created
204Deleted (No content)
400Bad Request
401Unauthorized
403Forbidden
404Not found
405Method not allowed

Define our REST API

First of all let's define our API.
  • return all Todo entries: '/todos' : GET request 
  • create a new Todo entry : '/todos' : POST request 
  • delete a Todo : '/todos/{id}' : DELETE request 
  • update a Todo : '/todos/{id} : PUT request 
  • view a Todo: '/todos/{id}' : GET request

Create the starter project

  • Go to http://start.spring.io/
  • Enter Group and Artifact 
  • Select Web, H2, JPA and Lombok dependencies 
  • Click Generate Project to generate and download the project





Modify the starter

  • Create HelloController and add following,

  • Go to project location and run the project
         gradle bootrun



Congratulations!!! you just created your first service ;)