Showing posts with label spring-boot. Show all posts

Passing and validating RequestParam in spring-boot rest api

In my previous article Creating first rest api in spring-boot we learned how you can create rest api. Now lets learn how you can pass parameters to api and validate it. In this example I'm going to use code from my previous article or you can head to Spring Tutorials page.

@RequestParam
Annotation which indicates that a method parameter should be bound to a web request parameter.

Source code (HelloWorldController.java)
import javax.validation.constraints.Size;

import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author javaQuery
 * @since 2018-01-31
 * @github https://github.com/javaquery/spring-boot-examples
 */
@RestController
@RequestMapping("/api")
@Validated
public class HelloWorldController {
 
 /**
  * This will send Hello {name-from-parameter} in response with HTTP status code 200.
  * @since 2018-02-01
  * @param firstname
  * @param lastname
  * @return
  */
   @GetMapping("/hello")
   public ResponseEntity<?> sayHello(
     @RequestParam @Size(min= 1, max = 5, message = "firstname length must be between 1 and 5") String firstname,
     @RequestParam String middlename,
     @RequestParam(required = false) String lastname){
    /* check lastname value */
    lastname = lastname != null ? lastname : "{lastname-is-optional}";
    return ResponseEntity.ok("Hello " + firstname + " " + middlename + " " + lastname);
   }
}
Request parameter syntax
Using @RequestParam spring rest api accept parameters from the request. You can also use various annotation from package javax.validation.constraints with @RequestParam.
@RequestParam <data_type> <variable_name>;

Lets quickly understand annotations used in HelloWorldController.java. As we already discussed few annotations in Creating first rest api in spring-boot so we will talk about new annotations only.

  • @Validated - To perform validation on each method of controller if any.
  • @RequestParam - To accept web request parameter in variable. (Note: All variable annotated with @RequestParam are compulsory/mandatory for request, until you set required = false @RequestParam(required = false) for that parameter)
Request parameter variations
@RequestParam @Size(min= 1, max = 5 , message = "firstname length must be between 1 and 5") String firstname
- @Size of package javax.validation.constraints is used to validate length of parameter in request and will throw ConstraintViolationException if data is not valid.
@RequestParam String middlename
- Accept mandatory parameter in variable middlename. If parameter is not present in request then spring will throw MissingServletRequestParameterException.
@RequestParam(required = false) String lastname
- Accept optional parameter in variable lastname.

Exception Handling
For exception org.springframework.web.bind.MissingServletRequestParameterException and javax.validation.ConstraintViolationException, spring will send 500 (Internal Server Error) in response so we'll catch those exception and send customized response.

Source code (RestExceptionHandler.java)
Used to catch exception thrown.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

/**
 * @author javaQuery
 * @since2018-02-01
 */
@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice()
public class RestExceptionHandler extends ResponseEntityExceptionHandler{
 
   @Override
   protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex, HttpHeaders headers,
     HttpStatus status, WebRequest request) {
    String error = ex.getParameterName() + " parameter is missing.";
    return new ResponseEntity<Object>(new ErrorResponse<>(Arrays.asList(error)), HttpStatus.BAD_REQUEST);
   }
 
   /**
    * Exception thrown when {@link org.springframework.validation.annotation.Validated} is used in controller.
    * @param ex
    * @param request
    * @return
    */
   @ExceptionHandler(ConstraintViolationException.class)
   protected ResponseEntity<?> handleConstraintViolationException(ConstraintViolationException ex, HttpServletRequest request) {
    try {
     List<String> messages = ex.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.toList());
     return new ResponseEntity<>(new ErrorResponse<>(messages), HttpStatus.BAD_REQUEST);
    } catch (Exception e) {
     return new ResponseEntity<>(new ErrorResponse<>(Arrays.asList(ex.getMessage())), HttpStatus.INTERNAL_SERVER_ERROR);
    }
   }
}
Source code (ErrorResponse.java)
Used to wrap the error message for response.
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;

/**
 * @author javaQuery
 * @since 2018-02-01
 * 
 * @param <T>
 */
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
public class ErrorResponse<T> {
   private List<T> errors = new ArrayList<>(1);
 
   public ErrorResponse(List<T> errors) {
    this.errors = errors;
   }
 
   public List<T> getErrors() {
    return errors;
   }
}

Request/Response
cURL GET http://localhost:8080/api/hello
-code 400
-body {"errors":["firstname parameter is missing."]}
cURL GET http://localhost:8080/api/hello?firstname=&middlename=v
-code 400
-body {"errors":["firstname length must be between 1 and 5"]}
cURL GET http://localhost:8080/api/hello?firstname=vicky&middlename=v
-code 200
-body Hello vicky v {lastname-is-optional}
cURL GET http://localhost:8080/api/hello?firstname=vicky&middlename=v&lastname=thakor
-code 200
-body Hello vicky v thakor

Creating first rest api in spring-boot

spring-boot
Today we are going to learn how to create rest api in spring-boot. This example is created using gradle, if you are not familiar with how to setup gradle project in eclipse follow the steps stated in Setup first gradle project in eclipse

build.gradle
update your build.gradle as follow and refresh the project, gradle will download the required dependencies(jar files).
buildscript {
    ext {
        springBootVersion = '1.5.7.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-web')
}

Source code (HelloWorldController.java)
Spring follows Model-View-Controller so we'll use widely used package structure and filenames. Now create package like com.example.package.rest.controller
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author javaQuery
 * @since 2018-01-31
 * @github https://github.com/javaquery/spring-boot-examples
 */
@RestController
@RequestMapping("/api") 
public class HelloWorldController {
 
 /**
  * This will send Hello World in response with HTTP status code 200.
  * @return
  */
 @GetMapping("/helloworld")
 public ResponseEntity sayHello(){
  /* return response */
  return ResponseEntity.ok("Hello World");
 }
}
Lets quickly understand annotations used in HelloWorldController.java

  • @RestController - To denote class will be service as rest service
  • @RequestMapping("/api") - default/root path for all apis created under HelloWorldController.java
  • @GetMapping("/helloworld") - sayHello method will serve for GET http request made for path /api/helloworld

Source code (Application.java)
Create Application.java (main-class) in package best suited your project,
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

/**
 * @author javaQuery
 * @since 2018-01-31
 * @github https://github.com/javaquery/spring-boot-examples
 */
@SpringBootApplication
@ComponentScan(basePackages = { "com.javaquery.examples.springboot.rest" })
public class Application {
 public static void main(String[] args) {
  SpringApplication.run(Application.class, args);
 }
}
Lets quickly understand annotations used in Application.java

  • @SpringBootApplication - denotes entry point of spring-boot application
  • @ComponentScan - files under given package(s) are part/component of spring application so spring will process the annotations.
Now run Application.java like any other java application with main method. It'll start local server and your rest API is ready to test. Open up localhost:8080/api/helloworld in your browser.

Project Structure

Source code is also available on my github repository: https://github.com/javaquery/spring-boot-examples. You can also check spring tutorials on http://www.javaquery.com/p/spring-tutorials.html and new you can do Passing and validating RequestParam in spring-boot rest api