Book Image

Building a RESTful Web Service with Spring

By : Ludovic Dewailly
Book Image

Building a RESTful Web Service with Spring

By: Ludovic Dewailly

Overview of this book

Table of Contents (17 chapters)
Building a RESTful Web Service with Spring
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Creating resources


The inventory component of our sample property management system deals with rooms. In Chapter 3, The First Endpoint, we built an endpoint to access rooms. Let's take a look at how to define an endpoint for creating new resources:

@RestController
@RequestMapping("/rooms")
public class RoomsResource {

  @RequestMapping(method = RequestMethod.POST)
  public ApiResponse addRoom(@RequestBody RoomDTO room) {
    Room newRoom = createRoom(room);
    return new ApiResponse(Status.OK, new RoomDTO(newRoom));
  }
}

We've added a new method to our RoomsResource class to handle the creation of new rooms. As described in Chapter 3, The First Endpoint, @RequestMapping is used to map requests to the Java method. Here, we map POST requests to addRoom().

Tip

Not specifying a value (path) in @RequestMapping is equivalent to using "/".

We pass the new room as a @RequestBody annotation. This annotation instructs Spring to map the body of the incoming web request to the method parameter. Jackson...