Spring boot restful API

Restful API expresses CRUD operations through HTTP, the following is a set of Restful APIs to add, delete, modify and list FX currency values.

URLHTTP Methodfunction
/fxPOSTlist all the FX values
/fx/{id}GETget FX values
/fx/{id}DELETEdelete FX
/fx/{id}PUTupdate FX

The URL is only the way to identify the resource, and the specific behavior is specified by the HTTP method

Now let’s take a look at how to implement the above interface

 @RestController
 @RequestMapping("/rest")
 public class FxRestController {
  
     @Autowired
     private FxService fxService;
  
     @RequestMapping(value = "/fx", method = POST, produces = "application/json")
     public WebResponse<Map<String, Object>> saveFx(@RequestBody Fx fx) {
         fx.setUserId(1L);
         fxService.saveFx(fx);
         Map<String, Object> ret = new HashMap<>();
         ret.put("id", fx.getId());
         WebResponse<Map<String, Object>> response = WebResponse.getSuccessResponse(ret);
         return response;
     }
  
     @RequestMapping(value = "/fx/{id}", method = DELETE, produces = "application/json")
     public WebResponse<?> deleteFx(@PathVariable Long id) {
         Fx fx = fxService.getById(id);
         fx.setStatus(-1);
         fxService.updateFx(fx);
         WebResponse<Object> response = WebResponse.getSuccessResponse(null);
         return response;
     }
  
     @RequestMapping(value = "/fx/{id}", method = PUT, produces = "application/json")
     public WebResponse<Object> updateFx(@PathVariable Long id, @RequestBody Fx fx) {
         fx.setId(id);
         fxService.updateFx(fx);
         WebResponse<Object> response = WebResponse.getSuccessResponse(null);
         return response;
     }
  
     @RequestMapping(value = "/fx/{id}", method = GET, produces = "application/json")
     public WebResponse<Article> getFx(@PathVariable Long id) {
         Fx fx = fxService.getById(id);
         WebResponse<Fx> response = WebResponse.getSuccessResponse(fx);
         return response;
     }
 } 

Let’s analyze this code again.

  1. We use the @RestController instead of @Controller, but this is also not provided by Spring boot, but provided in Spring MVC4
  2. There are three URL mappings in this class that are the same, they are all /fx/{id}, which is not allowed in the class @Controller.
  3. The @PathVariable is also provided by Spring MVC

So it seems that this code still has nothing to do with Spring boot. Spring boot only provides automatic configuration functions.

Let’s send some http requests with postman to see the results.

This entry was posted in Development and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published.