{"id":13247,"date":"2013-05-28T16:00:48","date_gmt":"2013-05-28T13:00:48","guid":{"rendered":"http:\/\/www.javacodegeeks.com\/?p=13247"},"modified":"2013-06-13T18:21:50","modified_gmt":"2013-06-13T15:21:50","slug":"spring-from-the-trenches-adding-validation-to-a-rest-api","status":"publish","type":"post","link":"https:\/\/www.javacodegeeks.com\/2013\/05\/spring-from-the-trenches-adding-validation-to-a-rest-api.html","title":{"rendered":"Spring from the Trenches: Adding Validation to a REST API"},"content":{"rendered":"<p>I am a bit ashamed to admit this but until yesterday, I had no idea that I can add validation to a REST API by using the <em>@Valid<\/em> and the <em>@RequestBody<\/em> annotations. This was not working in Spring MVC 3.0 and for some reason I had not noticed that the <a href=\"http:\/\/blog.goyello.com\/2011\/12\/16\/enhancements-spring-mvc31\/\" target=\"_blank\">support for this was added in Spring MVC 3.1<\/a>. I never liked the old approach because I had to<\/p>\n<ol>\n<li>Inject the <em>Validator<\/em> and <em>MessageSource<\/em> beans to my controller so that I can validate the request and fetch the localized error messages if the validation fails.<\/li>\n<li>Call the validation method in every controller method which input must be validated.<\/li>\n<li>Move the validation logic into a common base class which is extended by the controller classes.<\/li>\n<\/ol>\n<p>When I noticed that I don\u2019t have to do these things anymore, I decided to write this blog post and share my findings with all of you.<\/p>\n<p><strong>Note:<\/strong> If we want to use the JSR-303 backed validation with Spring Framework, we have to add a JSR-303 provider to our classpath. The example applications of this blog post use Hibernate Validator 4.2.0 which is the reference implementation of the Bean Validation API (JSR-303).<\/p>\n<p>Let\u2019s start by taking a look at the DTO class used in this blog post. The source code of the <em>CommentDTO<\/em> class looks as follows:<\/p>\n<pre class=\"brush:java\">import org.hibernate.validator.constraints.Length;\r\nimport org.hibernate.validator.constraints.NotEmpty;\r\n\r\npublic class CommentDTO {\r\n\r\n    @NotEmpty\r\n    @Length(max = 140)\r\n    private String text;\r\n\r\n    \/\/Methods are omitted.\r\n}<\/pre>\n<p>Let\u2019s move on and find out how we can add validation to a REST API with Spring MVC 3.1.<\/p>\n<h2>Spring MVC 3.1 Is a Good Start<\/h2>\n<p>We can add validation to our REST API by following these steps:<\/p>\n<ol>\n<li>Implement a controller method and ensure that its input is validated.<\/li>\n<li>Implement the logic which handles validation errors.<\/li>\n<\/ol>\n<p>Both of the steps are described in the following subsections.<\/p>\n<h4>Implementing the Controller<\/h4>\n<p>We can implement our controller by following these steps:<\/p>\n<ol>\n<li>Create a class called <em>CommentController<\/em> and annotate this class with the <em>@Controller<\/em> annotation.<\/li>\n<li>Add an <em>add()<\/em> method to the <em>CommentController<\/em> class which takes the added comment as a method parameter.<\/li>\n<li>Annotate the method with <em>@RequestMapping<\/em> and @ResponseBody annotations.<\/li>\n<li>Apply the <em>@Valid<\/em> and <em>@RequestBody<\/em> annotations to the method parameter.<\/li>\n<li>Return the added comment.<\/li>\n<\/ol>\n<p>The source code of the <em>CommentController<\/em> class looks as follows:<\/p>\n<pre class=\"brush:java\">import org.springframework.beans.factory.annotation.Autowired;\r\nimport org.springframework.http.HttpStatus;\r\nimport org.springframework.stereotype.Controller;\r\nimport org.springframework.web.bind.annotation.*;\r\n\r\nimport javax.validation.Valid;\r\n\r\n@Controller\r\npublic class CommentController {\r\n\r\n    @RequestMapping(value = \"\/api\/comment\", method = RequestMethod.POST)\r\n    @ResponseBody\r\n    public CommentDTO add(@Valid @RequestBody CommentDTO comment) {\r\n        return comment;\r\n    }\r\n}<\/pre>\n<p>We have now added a new method to our controller and added validation to it. When the validation fails, a <em>MethodArgumentNotValidException<\/em> is thrown. Let\u2019s find out how we can return a meaningful response to the user of our API when the validation fails.<\/p>\n<h4>Handling Validation Errors<\/h4>\n<p>We can implement the logic which handles the validation errors by following these steps:<\/p>\n<ol>\n<li>Implement the data transfer objects which contains the information returned to the user of our REST API.<\/li>\n<li>Implement the exception handler method.<\/li>\n<\/ol>\n<p>These steps are described with more details in the following.<\/p>\n<h2>Creating the Data Transfer Objects<\/h2>\n<p>First, we have to create the data transfer objects which contains the information returned to the user of our REST API. We can do this by following these steps:<\/p>\n<ol>\n<li>Create a DTO which contains the information of a single validation error.<\/li>\n<li>Create a DTO which wraps those validation errors together.<\/li>\n<\/ol>\n<p>Let\u2019s get started.<\/p>\n<p>The source code of the first DTO looks as follows:<\/p>\n<pre class=\"brush:java\">public class FieldErrorDTO {\r\n\r\n    private String field;\r\n\r\n    private String message;\r\n\r\n    public FieldErrorDTO(String field, String message) {\r\n        this.field = field;\r\n        this.message = message;\r\n    }\r\n\r\n    \/\/Getters are omitted.\r\n}<\/pre>\n<p>The implementation of the second DTO is rather simple. It contains a list of <em>FieldErrorDTO<\/em> objects and a method which is used to add new field errors to the list. The source code of the <em>ValidationErrorDTO<\/em> looks as follows:<\/p>\n<pre class=\"brush:java\">import java.util.ArrayList;\r\nimport java.util.List;\r\n\r\npublic class ValidationErrorDTO {\r\n\r\n    private List&lt;FieldErrorDTO&gt; fieldErrors = new ArrayList&lt;&gt;();\r\n\r\n    public ValidationErrorDTO() {\r\n\r\n    }\r\n\r\n    public void addFieldError(String path, String message) {\r\n        FieldErrorDTO error = new FieldErrorDTO(path, message);\r\n        fieldErrors.add(error);\r\n    }\r\n\r\n    \/\/Getter is omitted.\r\n}<\/pre>\n<p>The following listing provides an example Json document which is send back to the user of our API when the validation fails:<div style=\"display:inline-block; margin: 15px 0;\"> <div id=\"adngin-JavaCodeGeeks_incontent_video-0\" style=\"display:inline-block;\"><\/div> <\/div><\/p>\n<pre class=\"brush:java\">{\r\n    \"fieldErrors\":[\r\n        {\r\n            \"field\":\"text\",\r\n            \"message\":\"error message\"\r\n        }\r\n    ]\r\n}<\/pre>\n<p>Let\u2019s see how we can implement the exception handler method which creates a new <em>ValidationErrorDTO<\/em> object and returns created object.<\/p>\n<h2>Implementing the Exception Handler Method<\/h2>\n<p>We can add the exception handler method to our controller by following these steps:<\/p>\n<ol>\n<li>Add a <em>MessageSource<\/em> field to the <em>CommentController<\/em> class. The message source is used to fetch localized error message for validation errors.<\/li>\n<li>Inject the <em>MessageSource<\/em> bean by using constructor injection.<\/li>\n<li>Add a <em>processValidationError()<\/em> method to the <em>CommentController<\/em> class. This method returns <em>ValidationErrorDTO<\/em> object and takes a <em>MethodArgumentNotValidException<\/em> object as a method parameter.<\/li>\n<li>Annotate the method with the <em>@ExceptionHandler<\/em> annotation and ensure that the method is called when the <em>MethodArgumentNotValidException<\/em> is thrown.<\/li>\n<li>Annotate the method with the <em>@ResponseStatus<\/em> annotation and ensure that the HTTP status code 400 (bad request) is returned.<\/li>\n<li>Annotate the method with the <em>@ResponseBody<\/em> annotation.<\/li>\n<li>Implement the method.<\/li>\n<\/ol>\n<p>Let\u2019s take a closer look at the implementation of the <em>processValidationError()<\/em> method. We can implement this method by following these steps:<\/p>\n<ol>\n<li>Get a list of <em>FieldError<\/em> objects and process them.<\/li>\n<li>Process the field errors one field error at the time.<\/li>\n<li>Try to resolve a localized error message by using the <em>MessageSource<\/em> object, current locale and the error code of the processed field error.<\/li>\n<li>Return the resolved error message. If the error message is not found from the properties file, return the most accurate field error code.<\/li>\n<li>Add a new field error by calling the <em>addFieldError()<\/em> method of the <em>ValidationErrorDTO<\/em> class. Pass the name of the field and the resolved error message as method parameters.<\/li>\n<li>Return the created <em>ValidationErrorDTO<\/em> object after each field error has been processed.<\/li>\n<\/ol>\n<p>The source code of the CommentController class looks as follows:<\/p>\n<pre class=\"brush:java\">import org.springframework.beans.factory.annotation.Autowired;\r\nimport org.springframework.context.MessageSource;\r\nimport org.springframework.context.i18n.LocaleContextHolder;\r\nimport org.springframework.http.HttpStatus;\r\nimport org.springframework.stereotype.Controller;\r\nimport org.springframework.validation.BindingResult;\r\nimport org.springframework.validation.FieldError;\r\nimport org.springframework.web.bind.MethodArgumentNotValidException;\r\nimport org.springframework.web.bind.annotation.*;\r\n\r\nimport javax.validation.Valid;\r\nimport java.util.List;\r\nimport java.util.Locale;\r\n\r\n@Controller\r\npublic class CommentController {\r\n\r\n    private MessageSource messageSource;\r\n\r\n    @Autowired\r\n    public CommentController(MessageSource messageSource) {\r\n        this.messageSource = messageSource;\r\n    }\r\n\r\n    \/\/The add() method is omitted.\r\n\r\n    @ExceptionHandler(MethodArgumentNotValidException.class)\r\n    @ResponseStatus(HttpStatus.BAD_REQUEST)\r\n    @ResponseBody\r\n    public ValidationErrorDTO processValidationError(MethodArgumentNotValidException ex) {\r\n        BindingResult result = ex.getBindingResult();\r\n        List&lt;FieldError&gt; fieldErrors = result.getFieldErrors();\r\n\r\n        return processFieldErrors(fieldErrors);\r\n    }\r\n\r\n    private ValidationErrorDTO processFieldErrors(List&lt;FieldError&gt; fieldErrors) {\r\n        ValidationErrorDTO dto = new ValidationErrorDTO();\r\n\r\n        for (FieldError fieldError: fieldErrors) {\r\n            String localizedErrorMessage = resolveLocalizedErrorMessage(fieldError);\r\n            dto.addFieldError(fieldError.getField(), localizedErrorMessage);\r\n        }\r\n\r\n        return dto;\r\n    }\r\n\r\n    private String resolveLocalizedErrorMessage(FieldError fieldError) {\r\n        Locale currentLocale =  LocaleContextHolder.getLocale();\r\n        String localizedErrorMessage = messageSource.getMessage(fieldError, currentLocale);\r\n\r\n        \/\/If the message was not found, return the most accurate field error code instead.\r\n        \/\/You can remove this check if you prefer to get the default error message.\r\n        if (localizedErrorMessage.equals(fieldError.getDefaultMessage())) {\r\n            String[] fieldErrorCodes = fieldError.getCodes();\r\n            localizedErrorMessage = fieldErrorCodes[0];\r\n        }\r\n\r\n        return localizedErrorMessage;\r\n    }\r\n}<\/pre>\n<p>That is it. Let\u2019s spend a moment to evaluate what we have just done.<\/p>\n<h4>We Are Almost There<\/h4>\n<p>We have now added validation to our REST API with Spring MVC 3.1. This implementation has one major benefit over the old approach:<\/p>\n<p>We can trigger the validation process by using the <em>@Valid<\/em> annotation.<\/p>\n<p>However, the methods annotated with the <em>@ExceptionHandler<\/em> annotation will be triggered only when the configured exception is thrown from the controller class which contains the exception handler method. This means that if our application has more than one controller, we have to create a common base class for our controllers and move the logic which handles the validation errors to that class. This might not sound like a big deal but we should <a href=\"http:\/\/ron.shoutboot.com\/2012\/07\/27\/composition-over-inheritance\/\" target=\"_blank\">prefer composition over inheritance<\/a>.<\/p>\n<p>Spring MVC 3.2 provides the tools which we can use to remove the need of inheritance from our controllers. Let\u2019s move on and find out how this is done.<\/p>\n<h2>Spring MVC 3.2 to the Rescue<\/h2>\n<p><a href=\"http:\/\/static.springsource.org\/spring-framework\/docs\/3.2.x\/spring-framework-reference\/htmlsingle\/#new-in-3.2-webmvc-controller-advice\" target=\"_blank\">Spring MVC 3.2 introduced a new <em>@ControllerAdvice<\/em> annotation<\/a> which we can use to implement an exception handler component that processes the exceptions thrown by our controllers. We can implement this component by following these steps:<\/p>\n<ol>\n<li>Remove the logic which handles validation errors from the <em>CommentController<\/em> class.<\/li>\n<li>Create a new exception handler class and move the logic which processes validation errors to the created class.<\/li>\n<\/ol>\n<p>These steps are explained with more details in the following subsections.<\/p>\n<h4>Removing Exception Handling Logic from Our Controller<\/h4>\n<p>We can remove the exception handling logic from our controller by following these steps:<\/p>\n<ol>\n<li>Remove the <em>MessageSource<\/em> field from the <em>CommentController<\/em> class.<\/li>\n<li>Remove the constructor from our controller class.<\/li>\n<li>Remove the <em>processValidationError()<\/em> method and the private methods from our controller class.<\/li>\n<\/ol>\n<p>The source code of the <em>CommentController<\/em> class looks as follows:<\/p>\n<pre class=\"brush:java\">import org.springframework.stereotype.Controller;\r\nimport org.springframework.web.bind.annotation.*;\r\n\r\nimport javax.validation.Valid;\r\n\r\n@Controller\r\npublic class CommentController {\r\n\r\n    @RequestMapping(value = \"\/api\/comment\", method = RequestMethod.POST)\r\n    @ResponseBody\r\n    public CommentDTO add(@Valid @RequestBody CommentDTO comment) {\r\n        return comment;\r\n    }\r\n}<\/pre>\n<p>Our is next step is to create the exception handler component. Let\u2019s see how this is done.<\/p>\n<h4>Creating the Exception Handler Component<\/h4>\n<p>We can create the exception handler component by following these steps:<\/p>\n<ol>\n<li>Create a class called <em>RestErrorHandler<\/em> and annotate it with the <em>@ControllerAdvice<\/em> annotation.<\/li>\n<li>Add a <em>MessageSource<\/em> field to the <em>RestErrorHandler<\/em> class.<\/li>\n<li>Inject the <em>MessageSource<\/em> bean by using constructor injection.<\/li>\n<li>Add the <em>processValidationError()<\/em> method and the required private methods to the <em>RestErrorHandler<\/em> class.<\/li>\n<\/ol>\n<p>The source code of the RestErrorHandler class looks as follows:<\/p>\n<pre class=\"brush:java\">import org.springframework.beans.factory.annotation.Autowired;\r\nimport org.springframework.context.MessageSource;\r\nimport org.springframework.context.i18n.LocaleContextHolder;\r\nimport org.springframework.http.HttpStatus;\r\nimport org.springframework.validation.BindingResult;\r\nimport org.springframework.validation.FieldError;\r\nimport org.springframework.web.bind.MethodArgumentNotValidException;\r\nimport org.springframework.web.bind.annotation.ControllerAdvice;\r\nimport org.springframework.web.bind.annotation.ExceptionHandler;\r\nimport org.springframework.web.bind.annotation.ResponseBody;\r\nimport org.springframework.web.bind.annotation.ResponseStatus;\r\n\r\nimport java.util.List;\r\nimport java.util.Locale;\r\n\r\n@ControllerAdvice\r\npublic class RestErrorHandler {\r\n\r\n    private MessageSource messageSource;\r\n\r\n    @Autowired\r\n    public RestErrorHandler(MessageSource messageSource) {\r\n        this.messageSource = messageSource;\r\n    }\r\n\r\n    @ExceptionHandler(MethodArgumentNotValidException.class)\r\n    @ResponseStatus(HttpStatus.BAD_REQUEST)\r\n    @ResponseBody\r\n    public ValidationErrorDTO processValidationError(MethodArgumentNotValidException ex) {\r\n        BindingResult result = ex.getBindingResult();\r\n        List&lt;FieldError&gt; fieldErrors = result.getFieldErrors();\r\n\r\n        return processFieldErrors(fieldErrors);\r\n    }\r\n\r\n    private ValidationErrorDTO processFieldErrors(List&lt;FieldError&gt; fieldErrors) {\r\n        ValidationErrorDTO dto = new ValidationErrorDTO();\r\n\r\n        for (FieldError fieldError: fieldErrors) {\r\n            String localizedErrorMessage = resolveLocalizedErrorMessage(fieldError);\r\n            dto.addFieldError(fieldError.getField(), localizedErrorMessage);\r\n        }\r\n\r\n        return dto;\r\n    }\r\n\r\n    private String resolveLocalizedErrorMessage(FieldError fieldError) {\r\n        Locale currentLocale =  LocaleContextHolder.getLocale();\r\n        String localizedErrorMessage = messageSource.getMessage(fieldError, currentLocale);\r\n\r\n        \/\/If the message was not found, return the most accurate field error code instead.\r\n        \/\/You can remove this check if you prefer to get the default error message.\r\n        if (localizedErrorMessage.equals(fieldError.getDefaultMessage())) {\r\n            String[] fieldErrorCodes = fieldError.getCodes();\r\n            localizedErrorMessage = fieldErrorCodes[0];\r\n        }\r\n\r\n        return localizedErrorMessage;\r\n    }\r\n}<\/pre>\n<h4>We Are Finally There<\/h4>\n<p>Thanks to Spring MVC 3.2, we have now implemented an elegant solution where the validation is triggered by the <em>@Valid<\/em> annotation, and the exception handling logic is moved to a separate class. I think that we can call it a day and enjoy the results of our work.<\/p>\n<h2>Summary<\/h2>\n<p>This blog post has taught us that<\/p>\n<ul>\n<li>If we want to add validation to a REST API when we are using Spring 3.0, we have to implement the validation logic ourself.<\/li>\n<li>Spring 3.1 made it possible to add validation to a REST API by using the <em>@Valid<\/em> annotation. However, we have to create a common base class which contains the exception handling logic. Each controller which requires validation must extend this base class.<\/li>\n<li>When we are using Spring 3.2, we can trigger the validation process by using the <em>@Valid<\/em> annotation and extract the exception handling logic into a separate class.<\/li>\n<\/ul>\n<p>The example application of this blog are available at Github (<a href=\"https:\/\/github.com\/pkainulainen\/spring-from-the-trenches\/tree\/master\/rest-validation-3.1\" target=\"_blank\">Spring 3.1<\/a> and <a href=\"https:\/\/github.com\/pkainulainen\/spring-from-the-trenches\/tree\/master\/rest-validation-3.2\" target=\"_blank\">Spring 3.2<\/a>)<br \/>\n&nbsp;<\/p>\n<div style=\"border: 1px solid #D8D8D8; background: #FAFAFA; width: 100%; padding-left: 5px;\"><b><i>Reference: <\/i><\/b><a href=\"http:\/\/www.petrikainulainen.net\/programming\/spring-framework\/spring-from-the-trenches-adding-validation-to-a-rest-api\/\">Spring from the Trenches: Adding Validation to a REST API<\/a> from our <a href=\"http:\/\/www.javacodegeeks.com\/jcg\">JCG partner<\/a> Petri Kainulainen at the <a href=\"http:\/\/www.petrikainulainen.net\/\">Petri Kainulainen<\/a> blog.<\/div>\n","protected":false},"excerpt":{"rendered":"<p>I am a bit ashamed to admit this but until yesterday, I had no idea that I can add validation to a REST API by using the @Valid and the @RequestBody annotations. This was not working in Spring MVC 3.0 and for some reason I had not noticed that the support for this was added &hellip;<\/p>\n","protected":false},"author":429,"featured_media":240,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[8],"tags":[54,30],"class_list":["post-13247","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-enterprise-java","tag-restful-web-services","tag-spring"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.5 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Spring from the Trenches: Adding Validation to a REST API<\/title>\n<meta name=\"description\" content=\"I am a bit ashamed to admit this but until yesterday, I had no idea that I can add validation to a REST API by using the @Valid and the @RequestBody\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.javacodegeeks.com\/2013\/05\/spring-from-the-trenches-adding-validation-to-a-rest-api.html\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Spring from the Trenches: Adding Validation to a REST API\" \/>\n<meta property=\"og:description\" content=\"I am a bit ashamed to admit this but until yesterday, I had no idea that I can add validation to a REST API by using the @Valid and the @RequestBody\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.javacodegeeks.com\/2013\/05\/spring-from-the-trenches-adding-validation-to-a-rest-api.html\" \/>\n<meta property=\"og:site_name\" content=\"Java Code Geeks\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/javacodegeeks\" \/>\n<meta property=\"article:published_time\" content=\"2013-05-28T13:00:48+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2013-06-13T15:21:50+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/spring-logo.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"150\" \/>\n\t<meta property=\"og:image:height\" content=\"150\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Petri Kainulainen\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/petrikainulaine\" \/>\n<meta name=\"twitter:site\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Petri Kainulainen\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"10 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2013\\\/05\\\/spring-from-the-trenches-adding-validation-to-a-rest-api.html#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2013\\\/05\\\/spring-from-the-trenches-adding-validation-to-a-rest-api.html\"},\"author\":{\"name\":\"Petri Kainulainen\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/person\\\/5af4df3fdfeb79e9fa3598d79bff2c9e\"},\"headline\":\"Spring from the Trenches: Adding Validation to a REST API\",\"datePublished\":\"2013-05-28T13:00:48+00:00\",\"dateModified\":\"2013-06-13T15:21:50+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2013\\\/05\\\/spring-from-the-trenches-adding-validation-to-a-rest-api.html\"},\"wordCount\":1432,\"commentCount\":9,\"publisher\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#organization\"},\"image\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2013\\\/05\\\/spring-from-the-trenches-adding-validation-to-a-rest-api.html#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/spring-logo.jpg\",\"keywords\":[\"RESTful Web Services\",\"Spring\"],\"articleSection\":[\"Enterprise Java\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.javacodegeeks.com\\\/2013\\\/05\\\/spring-from-the-trenches-adding-validation-to-a-rest-api.html#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2013\\\/05\\\/spring-from-the-trenches-adding-validation-to-a-rest-api.html\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2013\\\/05\\\/spring-from-the-trenches-adding-validation-to-a-rest-api.html\",\"name\":\"Spring from the Trenches: Adding Validation to a REST API\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2013\\\/05\\\/spring-from-the-trenches-adding-validation-to-a-rest-api.html#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2013\\\/05\\\/spring-from-the-trenches-adding-validation-to-a-rest-api.html#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/spring-logo.jpg\",\"datePublished\":\"2013-05-28T13:00:48+00:00\",\"dateModified\":\"2013-06-13T15:21:50+00:00\",\"description\":\"I am a bit ashamed to admit this but until yesterday, I had no idea that I can add validation to a REST API by using the @Valid and the @RequestBody\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2013\\\/05\\\/spring-from-the-trenches-adding-validation-to-a-rest-api.html#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.javacodegeeks.com\\\/2013\\\/05\\\/spring-from-the-trenches-adding-validation-to-a-rest-api.html\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2013\\\/05\\\/spring-from-the-trenches-adding-validation-to-a-rest-api.html#primaryimage\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/spring-logo.jpg\",\"contentUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/spring-logo.jpg\",\"width\":150,\"height\":150,\"caption\":\"spring-interview-questions-answers\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2013\\\/05\\\/spring-from-the-trenches-adding-validation-to-a-rest-api.html#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.javacodegeeks.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Java\",\"item\":\"https:\\\/\\\/www.javacodegeeks.com\\\/category\\\/java\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Enterprise Java\",\"item\":\"https:\\\/\\\/www.javacodegeeks.com\\\/category\\\/java\\\/enterprise-java\"},{\"@type\":\"ListItem\",\"position\":4,\"name\":\"Spring from the Trenches: Adding Validation to a REST API\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#website\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/\",\"name\":\"Java Code Geeks\",\"description\":\"Java Developers Resource Center\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#organization\"},\"alternateName\":\"JCG\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.javacodegeeks.com\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#organization\",\"name\":\"Exelixis Media P.C.\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2022\\\/06\\\/exelixis-logo.png\",\"contentUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2022\\\/06\\\/exelixis-logo.png\",\"width\":864,\"height\":246,\"caption\":\"Exelixis Media P.C.\"},\"image\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/www.facebook.com\\\/javacodegeeks\",\"https:\\\/\\\/x.com\\\/javacodegeeks\"]},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/person\\\/5af4df3fdfeb79e9fa3598d79bff2c9e\",\"name\":\"Petri Kainulainen\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/9e57425180f323fa65bc519a64c8273d3fcb7c6bd272e56b37dd15613f403659?s=96&d=mm&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/9e57425180f323fa65bc519a64c8273d3fcb7c6bd272e56b37dd15613f403659?s=96&d=mm&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/9e57425180f323fa65bc519a64c8273d3fcb7c6bd272e56b37dd15613f403659?s=96&d=mm&r=g\",\"caption\":\"Petri Kainulainen\"},\"description\":\"Petri is passionate about software development and continuous improvement. He is specialized in software development with the Spring Framework and is the author of Spring Data book.\",\"sameAs\":[\"http:\\\/\\\/www.petrikainulainen.net\\\/\",\"http:\\\/\\\/www.linkedin.com\\\/in\\\/petrikainulainen\",\"https:\\\/\\\/x.com\\\/https:\\\/\\\/twitter.com\\\/petrikainulaine\"],\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/author\\\/petri-kainulainen\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Spring from the Trenches: Adding Validation to a REST API","description":"I am a bit ashamed to admit this but until yesterday, I had no idea that I can add validation to a REST API by using the @Valid and the @RequestBody","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.javacodegeeks.com\/2013\/05\/spring-from-the-trenches-adding-validation-to-a-rest-api.html","og_locale":"en_US","og_type":"article","og_title":"Spring from the Trenches: Adding Validation to a REST API","og_description":"I am a bit ashamed to admit this but until yesterday, I had no idea that I can add validation to a REST API by using the @Valid and the @RequestBody","og_url":"https:\/\/www.javacodegeeks.com\/2013\/05\/spring-from-the-trenches-adding-validation-to-a-rest-api.html","og_site_name":"Java Code Geeks","article_publisher":"https:\/\/www.facebook.com\/javacodegeeks","article_published_time":"2013-05-28T13:00:48+00:00","article_modified_time":"2013-06-13T15:21:50+00:00","og_image":[{"width":150,"height":150,"url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/spring-logo.jpg","type":"image\/jpeg"}],"author":"Petri Kainulainen","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/petrikainulaine","twitter_site":"@javacodegeeks","twitter_misc":{"Written by":"Petri Kainulainen","Est. reading time":"10 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.javacodegeeks.com\/2013\/05\/spring-from-the-trenches-adding-validation-to-a-rest-api.html#article","isPartOf":{"@id":"https:\/\/www.javacodegeeks.com\/2013\/05\/spring-from-the-trenches-adding-validation-to-a-rest-api.html"},"author":{"name":"Petri Kainulainen","@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/person\/5af4df3fdfeb79e9fa3598d79bff2c9e"},"headline":"Spring from the Trenches: Adding Validation to a REST API","datePublished":"2013-05-28T13:00:48+00:00","dateModified":"2013-06-13T15:21:50+00:00","mainEntityOfPage":{"@id":"https:\/\/www.javacodegeeks.com\/2013\/05\/spring-from-the-trenches-adding-validation-to-a-rest-api.html"},"wordCount":1432,"commentCount":9,"publisher":{"@id":"https:\/\/www.javacodegeeks.com\/#organization"},"image":{"@id":"https:\/\/www.javacodegeeks.com\/2013\/05\/spring-from-the-trenches-adding-validation-to-a-rest-api.html#primaryimage"},"thumbnailUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/spring-logo.jpg","keywords":["RESTful Web Services","Spring"],"articleSection":["Enterprise Java"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.javacodegeeks.com\/2013\/05\/spring-from-the-trenches-adding-validation-to-a-rest-api.html#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.javacodegeeks.com\/2013\/05\/spring-from-the-trenches-adding-validation-to-a-rest-api.html","url":"https:\/\/www.javacodegeeks.com\/2013\/05\/spring-from-the-trenches-adding-validation-to-a-rest-api.html","name":"Spring from the Trenches: Adding Validation to a REST API","isPartOf":{"@id":"https:\/\/www.javacodegeeks.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.javacodegeeks.com\/2013\/05\/spring-from-the-trenches-adding-validation-to-a-rest-api.html#primaryimage"},"image":{"@id":"https:\/\/www.javacodegeeks.com\/2013\/05\/spring-from-the-trenches-adding-validation-to-a-rest-api.html#primaryimage"},"thumbnailUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/spring-logo.jpg","datePublished":"2013-05-28T13:00:48+00:00","dateModified":"2013-06-13T15:21:50+00:00","description":"I am a bit ashamed to admit this but until yesterday, I had no idea that I can add validation to a REST API by using the @Valid and the @RequestBody","breadcrumb":{"@id":"https:\/\/www.javacodegeeks.com\/2013\/05\/spring-from-the-trenches-adding-validation-to-a-rest-api.html#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.javacodegeeks.com\/2013\/05\/spring-from-the-trenches-adding-validation-to-a-rest-api.html"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.javacodegeeks.com\/2013\/05\/spring-from-the-trenches-adding-validation-to-a-rest-api.html#primaryimage","url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/spring-logo.jpg","contentUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/spring-logo.jpg","width":150,"height":150,"caption":"spring-interview-questions-answers"},{"@type":"BreadcrumbList","@id":"https:\/\/www.javacodegeeks.com\/2013\/05\/spring-from-the-trenches-adding-validation-to-a-rest-api.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.javacodegeeks.com\/"},{"@type":"ListItem","position":2,"name":"Java","item":"https:\/\/www.javacodegeeks.com\/category\/java"},{"@type":"ListItem","position":3,"name":"Enterprise Java","item":"https:\/\/www.javacodegeeks.com\/category\/java\/enterprise-java"},{"@type":"ListItem","position":4,"name":"Spring from the Trenches: Adding Validation to a REST API"}]},{"@type":"WebSite","@id":"https:\/\/www.javacodegeeks.com\/#website","url":"https:\/\/www.javacodegeeks.com\/","name":"Java Code Geeks","description":"Java Developers Resource Center","publisher":{"@id":"https:\/\/www.javacodegeeks.com\/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.javacodegeeks.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.javacodegeeks.com\/#organization","name":"Exelixis Media P.C.","url":"https:\/\/www.javacodegeeks.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/logo\/image\/","url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","contentUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/javacodegeeks","https:\/\/x.com\/javacodegeeks"]},{"@type":"Person","@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/person\/5af4df3fdfeb79e9fa3598d79bff2c9e","name":"Petri Kainulainen","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/9e57425180f323fa65bc519a64c8273d3fcb7c6bd272e56b37dd15613f403659?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/9e57425180f323fa65bc519a64c8273d3fcb7c6bd272e56b37dd15613f403659?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/9e57425180f323fa65bc519a64c8273d3fcb7c6bd272e56b37dd15613f403659?s=96&d=mm&r=g","caption":"Petri Kainulainen"},"description":"Petri is passionate about software development and continuous improvement. He is specialized in software development with the Spring Framework and is the author of Spring Data book.","sameAs":["http:\/\/www.petrikainulainen.net\/","http:\/\/www.linkedin.com\/in\/petrikainulainen","https:\/\/x.com\/https:\/\/twitter.com\/petrikainulaine"],"url":"https:\/\/www.javacodegeeks.com\/author\/petri-kainulainen"}]}},"_links":{"self":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/13247","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/users\/429"}],"replies":[{"embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/comments?post=13247"}],"version-history":[{"count":0,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/13247\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/media\/240"}],"wp:attachment":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/media?parent=13247"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/categories?post=13247"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/tags?post=13247"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}