基于SpringBoot创建REST服务
RESTful API
RESTful API的设计思想是基于动词+宾语的方式实现资源的操作,其表达更为直观。
主要的目的是为了方便快捷的支持CRUD操作。
支持的请求方式
- GET 【获取资源】
- POST 【新建资源】
- PUT【更新资源】
- PATCH【部分更新资源】
- DELETE【删除资源】
服务器响应
- 1XX 【相关信息】
- 2XX 【操作成功】
- 3XX【重定向】
- 4XX【客户端错误】
- 5XX【服务端错误】
URL设计示例
- GET
- /something 【获取全部】
- /something/id 【指定ID获取】
- POST
- /something 【新建】
- PUT
- /something/id 【指定ID修改】
- PATCH
- /something/id 【指定ID部分修改】
- DELETE
- /something/id 【指定ID删除】
SpringBoot实现RESTful API
一般在Controller层实现
/**
* @RequestMapping注释定义了最基础的访问接口
*/
@RequestMapping("/learn")
public class LearnController {
@Autowired
private Learn learn;
/**
* 获取所有Learn实例
* @return
*/
@GetMapping
public Learn getAllLearns(){
return learn;
}
/**
* 根据ID获取Learn实例
* @param id
* @return
*/
@GetMapping("{id}")
public Learn getLearnById(@PathVariable Integer id){
return learn;
}
/**
* 基于Post提交的请求体数据中的learn实例新建
* @param learn
* @return
*/
@PostMapping
public Boolean save(@RequestBody Learn learn){
return true;
}
/**
* 基于传入的id和请求体的learn对象更新实例信息
* @param id
* @param learn
* @return
*/
@PutMapping("{id}")
public Boolean updateById(@PathVariable Integer id, @RequestBody Learn learn){
return true;
}
/**
* 基于传入的id和请求体的learn对象更新实例信息
* @param id
* @param learn
* @return
*/
@PatchMapping("{id}")
public Boolean updatePatchById(@PathVariable Integer id, @RequestBody Learn learn){
return true;
}
/**
* 基于传入的id删除实例
* @param id
* @return
*/
@DeleteMapping("{id}")
public Boolean deleteById(@PathVariable Integer id){
return true;
}
}