Spring REST

Introduction

What is REST?

  • Compared to traditional MVC framework, an application will be separated into different parts so as to facilitate the maintenance and different parts of application can also be coded by different framework, such as nodeJS Express, java spring

  • In order to build the communication between each parts, the api url will be called by using Http

  • Each api call should be stateless

  • The common data format will be Json, Xml

Request

  • Http Method (Get, Post, Put, Delete)

  • Header (For additional information)

  • Body (passed in Json format)

Response

  • Status Code and Protocol

  • Header

  • Body(the return value)

Terminology

  • Data Binding separate into 2 parts

Serialization

  • Convert Object into Stream (JSON is one of the form of the stream to be transfer through http call)

Deserialization

  • Convert Stream into Object

Data Binding

Pre-Action

  • Install the dependency of FastXML Jackson

  • It is a dependency that bind the json into java POJO, otherwise, application/json format will not be accepted by api end point

Situation 1

Data

Situation 2

  • Json may contain another another json which have not a constant format

  • Json only contain value in string or number format, if we want convert the string into date in POJO, we need to do custom serialization and deserialization

Data

Custom Serializer and Deserializer

Controller

Situation 3

  • Sometimes, we may need to json in string format

  • we need to make good use of object mapper from Jackson to handle that

Main

Exception Handling

  • In some of the case, such as: the object cannot be found by using id entered by user

  • The error json should be returned in order to notice the user

Custom Exception

Error POJO

Exception Handler

Controller

Result

Last updated

Was this helpful?