公众号:阿区先生

RESTful接口设计风格

2020-10-04  本文已影响0人  砒霜拌辣椒

什么是RESTful风格?

1、HTTP方法与CRUD动作的映射

动作 普通CRUD的URL Restful的URL Restful对应的HTTP方法
查询 Article?id=1 Article/{id} GET
添加 Article?title=xxx&body=xxx Article POST
修改 Article/update?id=1 Article/{id} PUT/PATCH
删除 Article/delete?id=1 Article/{id} DELETE

其中PUTPATCH比较相似,都是做更新操作。PUT一般用于全部修改进行替换操作,PATCH用于更新部分字段(资源)操作。

2、RESTful API

2.1、查询列表

@RequestMapping(value = "/ArticleList", method = RequestMethod.GET)
public List<Article> getArticleList() {
    List<Article> articleList = articleRepository.findAll();
    return articleList;
}

2.2、增加内容

@RequestMapping(value = "/Article", method = RequestMethod.POST)
public String addArticle(Article article) {
    articleRepository.save(article);
    return "success";
}

2.3、删除内容

@RequestMapping(value = "/Article/{id}", method = RequestMethod.DELETE)
public String deleteArticle(@PathVariable("id") long id) {
    articleRepository.deleteById(id);
    return "success";
}

2.4、修改内容

@RequestMapping(value = "/Article/{id}", method = RequestMethod.PUT)
public String updateArticle(Article model) {
    articleRepository.save(model);
    return "success";
}

2.5、查询内容

@RequestMapping(value = "/Article/{id}", method = RequestMethod.GET)
public Article findArticle(@PathVariable("id") long id) {
    Article article = articleRepository.findById(id);
    return article;
}
上一篇 下一篇

猜你喜欢

热点阅读