关于restful接口命名问题

如果请求同一个资源,但是参数不同的怎么办?

clipboard.png

clipboard.png

像上面这两种情况的话,请求同一个列表,只是传参不一样 。如果path写一样的会报错,按照规范,这个path应该怎么命名呢?

阅读 3.4k
4 个回答
新手上路,请多包涵

基本的CRUD可按照resultFul来命名。其他功能可自定义,不用满足resultFul规范

/info/list?classType=?
/info/list?courseId=?

这种都是写一起的吧

第一种

@RequestMapping(path = "/info/list/{classType}/{courseId}", method = RequestMethod.GET)
public Info getInfoList(@PathVariable String classType, @PathVariable String courseId) {
    // code here
}

第二种

@RequestMapping(path = "/info/list", method = RequestMethod.GET)
public Info getInfoList(@RequestParam String classType, @RequestParam String courseId) {
    // code here
}

还有一种通用的方式,参照下面

比如你想设计的restful api是这样的,

http://localhost:2000/custom?brand=dell&limit=20&price=20000&sort=asc

那么想获得查询参数,可以采用map来获取,

    @RequestMapping(method = RequestMethod.GET, value = "/custom")
    public String controllerMethod(@RequestParam Map<String, String> customQuery) {

        System.out.println("customQuery = brand " + customQuery.containsKey("brand"));
        System.out.println("customQuery = limit " + customQuery.containsKey("limit"));
        System.out.println("customQuery = price " + customQuery.containsKey("price"));
        System.out.println("customQuery = other " + customQuery.containsKey("other"));
        System.out.println("customQuery = sort " + customQuery.containsKey("sort"));

        return customQuery.toString();
    }

希望能帮到你。

两种方法有冲突吗?

  • 有的话,可以list-by-typelist-by-id之类的
  • 没有的话,同一个接口接然后判断参数

加个 type 字段来去分

然后我想吐槽一下。你这个接口命名根本不是符合rest规范

你要查列表。正常不是get 然后+参数吗。加个 list 是干嘛用的

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题