airycanon
V2EX  ›  API

请教一个 RESTful API 的设计问题

  •  
  •   airycanon · Oct 23, 2017 · 2676 views
    This topic created in 3127 days ago, the information mentioned may be changed or developed.

    有如下两个表

    • 用户 users ( id,group_id,...)

    • 组 groups ( id,...)

    想要设计一个 API 把用户批量加入某个组,请问下面哪个 API 更好一些,或者有更好的方案?先谢过各位。

    • POST /users/add-to-group/{组 id}

      提交用户 id 数组

    • POST /groups/{组 id}/add-users

      提交用户 id 数组

    9 replies    2017-10-23 11:57:03 +08:00
    Sanko
        1
    Sanko  
       Oct 23, 2017 via Android
    直觉第一个吧
    whypool
        2
    whypool  
       Oct 23, 2017
    第一种;
    不过一般会把动作提到前面:post /groups/add-users/{id}
    pubby
        3
    pubby  
       Oct 23, 2017
    为啥不是 POST /groups/<gid>/users
    airycanon
        4
    airycanon  
    OP
       Oct 23, 2017
    @pubby 这不就是第二种么……
    pubby
        5
    pubby  
       Oct 23, 2017 via Android
    url 应该是资源,不是动作
    mcfog
        6
    mcfog  
       Oct 23, 2017
    这两个都是典型的 restful 反模式(动作写在 URL 里用 POST )

    user 和 group 的关系如果作为 group 资源的属性的话

    PATCH /group/<group_id>/users
    [...user_ids]
    或者(便于扩展批量删除等其他语义)
    {type: join, users: [...user_ids]}

    也可以把关系当作独立的资源
    POST /user-group-relation
    [...{user_id, group_id}]
    airycanon
        7
    airycanon  
    OP
       Oct 23, 2017
    @pubby @mcfog 两位说的意思我明白了,多谢指点。
    mec
        8
    mec  
       Oct 23, 2017
    楼上正解,restful uri 里面是资源,不能有动词
    动词用 http 里面的 method 区分,如果想丰富动作,可以添加参数 method 来区分
    TuringGooner
        9
    TuringGooner  
       Oct 23, 2017
    你这两个都不对

    要么重新重新抽象出来一个新的资源,就像楼上那样

    或者写一个 users controller,处理 users 这个资源,看你这个应该是在 users 里增加 group_id 吧
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2932 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 47ms · UTC 10:13 · PVG 18:13 · LAX 03:13 · JFK 06:13
    ♥ Do have faith in what you're doing.