Restful API expresses CRUD operations through HTTP, the following is a set of Restful APIs to add, delete, modify and list FX currency values.
URL | HTTP Method | function |
/fx | POST | list all the FX values |
/fx/{id} | GET | get FX values |
/fx/{id} | DELETE | delete FX |
/fx/{id} | PUT | update 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.
- We use the @RestController instead of @Controller, but this is also not provided by Spring boot, but provided in Spring MVC4
- 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.
- 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.