美文网首页
Spring boot Rest Api Example

Spring boot Rest Api Example

作者: ZzZephyr | 来源:发表于2018-11-13 18:56 被阅读0次

    Short & Quick introduction to REST

    REST stands for Representational State Transfer.It’s an is an architectural style which can be used to design web services, that can be consumed from a variety of clients. The core idea is that, rather than using complex mechanisms such as CORBA, RPC or SOAP to connect between machines, simple HTTP is used to make calls among them.

    In Rest based design, resources are being manipulated using a common set of verbs.

    To Create a resource : HTTP POST should be used

    To Retrieve a resource : HTTP GET should be used

    To Update a resource : HTTP PUT should be used

    To Delete a resource : HTTP DELETE should be used

    That means, you as a REST service developer or Client, should comply to above criteria, in order to be REST complained.

    Often Rest based Web services return JSON or XML as response, although it is not limited to these types only. Clients can specify (using HTTP Accept header) the resource type they are interested in, and server may return the resource , specifying Content-Type of the resource it is serving. This StackOverflow link is a must read to understand REST in detail.

    Sample code:

    packagecom.websystique.springboot.controller;

    importjava.util.List;

    importorg.slf4j.Logger;

    importorg.slf4j.LoggerFactory;

    importorg.springframework.beans.factory.annotation.Autowired;

    importorg.springframework.http.HttpHeaders;

    importorg.springframework.http.HttpStatus;

    importorg.springframework.http.ResponseEntity;

    importorg.springframework.web.bind.annotation.PathVariable;

    importorg.springframework.web.bind.annotation.RequestBody;

    importorg.springframework.web.bind.annotation.RequestMapping;

    importorg.springframework.web.bind.annotation.RequestMethod;

    importorg.springframework.web.bind.annotation.RestController;

    importorg.springframework.web.util.UriComponentsBuilder;

    importcom.websystique.springboot.model.User;

    importcom.websystique.springboot.service.UserService;

    importcom.websystique.springboot.util.CustomErrorType;

    @RestController

    @RequestMapping("/api")

    publicclassRestApiController {

        publicstaticfinalLogger logger = LoggerFactory.getLogger(RestApiController.class);

        @Autowired

        UserService userService; //Service which will do all data retrieval/manipulation work

        // -------------------Retrieve All Users---------------------------------------------

        @RequestMapping(value = "/user/", method = RequestMethod.GET)

        publicResponseEntity<List<User>> listAllUsers() {

            List<User> users = userService.findAllUsers();

            if(users.isEmpty()) {

                returnnewResponseEntity(HttpStatus.NO_CONTENT);

                // You many decide to return HttpStatus.NOT_FOUND

            }

            returnnewResponseEntity<List<User>>(users, HttpStatus.OK);

        }

        // -------------------Retrieve Single User------------------------------------------

        @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)

        publicResponseEntity<?> getUser(@PathVariable("id") longid) {

            logger.info("Fetching User with id {}", id);

            User user = userService.findById(id);

            if(user == null) {

                logger.error("User with id {} not found.", id);

                returnnewResponseEntity(newCustomErrorType("User with id "+ id

                        + " not found"), HttpStatus.NOT_FOUND);

            }

            returnnewResponseEntity<User>(user, HttpStatus.OK);

        }

        // -------------------Create a User-------------------------------------------

        @RequestMapping(value = "/user/", method = RequestMethod.POST)

        publicResponseEntity<?> createUser(@RequestBodyUser user, UriComponentsBuilder ucBuilder) {

            logger.info("Creating User : {}", user);

            if(userService.isUserExist(user)) {

                logger.error("Unable to create. A User with name {} already exist", user.getName());

                returnnewResponseEntity(newCustomErrorType("Unable to create. A User with name "+

                user.getName() + " already exist."),HttpStatus.CONFLICT);

            }

            userService.saveUser(user);

            HttpHeaders headers = newHttpHeaders();

            headers.setLocation(ucBuilder.path("/api/user/{id}").buildAndExpand(user.getId()).toUri());

            returnnewResponseEntity<String>(headers, HttpStatus.CREATED);

        }

        // ------------------- Update a User ------------------------------------------------

        @RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)

        publicResponseEntity<?> updateUser(@PathVariable("id") longid, @RequestBodyUser user) {

            logger.info("Updating User with id {}", id);

            User currentUser = userService.findById(id);

            if(currentUser == null) {

                logger.error("Unable to update. User with id {} not found.", id);

                returnnewResponseEntity(newCustomErrorType("Unable to upate. User with id "+ id + " not found."),

                        HttpStatus.NOT_FOUND);

            }

            currentUser.setName(user.getName());

            currentUser.setAge(user.getAge());

            currentUser.setSalary(user.getSalary());

            userService.updateUser(currentUser);

            returnnewResponseEntity<User>(currentUser, HttpStatus.OK);

        }

        // ------------------- Delete a User-----------------------------------------

        @RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)

        publicResponseEntity<?> deleteUser(@PathVariable("id") longid) {

            logger.info("Fetching & Deleting User with id {}", id);

            User user = userService.findById(id);

            if(user == null) {

                logger.error("Unable to delete. User with id {} not found.", id);

                returnnewResponseEntity(newCustomErrorType("Unable to delete. User with id "+ id + " not found."),

                        HttpStatus.NOT_FOUND);

            }

            userService.deleteUserById(id);

            returnnewResponseEntity<User>(HttpStatus.NO_CONTENT);

        }

        // ------------------- Delete All Users-----------------------------

        @RequestMapping(value = "/user/", method = RequestMethod.DELETE)

        publicResponseEntity<User> deleteAllUsers() {

            logger.info("Deleting All Users");

            userService.deleteAllUsers();

            returnnewResponseEntity<User>(HttpStatus.NO_CONTENT);

        }

    }

    publicclassCustomErrorType {

        privateString errorMessage;

        publicCustomErrorType(String errorMessage){

            this.errorMessage = errorMessage;

        }

        publicString getErrorMessage() {

            returnerrorMessage;

        }

    }

    相关文章

      网友评论

          本文标题:Spring boot Rest Api Example

          本文链接:https://www.haomeiwen.com/subject/vpolfqtx.html