V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
yujianwjj
V2EX  ›  Python

restful 接口,如何设计对某个资源的列表字段增加一个元素的操作?

  •  
  •   yujianwjj · 2017-08-01 15:14:21 +08:00 · 2529 次点击
    这是一个创建于 2450 天前的主题,其中的信息可能已经有所发展或是发生改变。
    "job": {
    	"id": 1,
    	"node": [1, 2, 3]
    }
    

    现在相对 node 字段增加一个元素 4,restful 的接口该如何写。

    14 条回复    2017-08-01 17:04:38 +08:00
    fangchang
        1
    fangchang  
       2017-08-01 15:18:59 +08:00
    post
    /job/{id}/nodes

    content: 4
    yujianwjj
        2
    yujianwjj  
    OP
       2017-08-01 15:21:56 +08:00
    你这个应该是将整个 nodes 字段替换为 4
    gigantic222
        3
    gigantic222  
       2017-08-01 15:25:18 +08:00 via iPhone
    Post {id}/nodes/push 加个参数当作动作吧 然后 shift pop 什么的同理
    gigantic222
        4
    gigantic222  
       2017-08-01 15:27:50 +08:00 via iPhone
    感觉还是直接 put 1,2,3,4 靠谱些
    ansheng
        5
    ansheng  
       2017-08-01 15:29:41 +08:00
    put
    /job/{id}/
    node=[1, 2, 3,4]
    mooncakejs
        6
    mooncakejs  
       2017-08-01 15:31:44 +08:00
    put /job/{id}
    {
    "node": [1, 2, 3,4]
    }
    如果要原子化
    1 楼的吧
    timwei
        7
    timwei  
       2017-08-01 15:35:09 +08:00
    1. 将 node 看做资源:
    post /job/{id}/nodes

    2. 将 job 看做资源,node 看做属性:
    put /job/{id}
    yujianwjj
        8
    yujianwjj  
    OP
       2017-08-01 15:38:44 +08:00
    @gigantic222 restful 接口好像是不推荐加动作参数。
    timwei
        9
    timwei  
       2017-08-01 15:39:55 +08:00
    @yujianwjj
    如果将 node 看做资源
    替换整组资源为 4,应对应到
    put /job/{id}/nodes
    fangchang
        10
    fangchang  
       2017-08-01 16:10:13 +08:00   ❤️ 1
    如果你要替换,那是对应的 put。
    post 在我看来就是用来在此资源里创建并添加。
    baiyi
        11
    baiyi  
       2017-08-01 16:21:04 +08:00
    看你的逻辑需求

    如果是创建一个 `node` 的话就用 `POST`

    如果是更新 `job` , 就是 `PUT`

    注意 `POST` 和 `PUT` 的区别

    `PUT` 有幂等性, 也就是说多次请求的效果是相同的

    所以说, 如果你的 `node` 里 `4` 这个值不能重叠的话, 也应该是 `PUT`
    wizardoz
        12
    wizardoz  
       2017-08-01 16:38:49 +08:00
    node 是资源,属性最好改为 nodes

    put /job/1/nodes/4
    paicha
        13
    paicha  
       2017-08-01 17:03:30 +08:00
    POST /job/1/nodes/
    otakustay
        14
    otakustay  
       2017-08-01 17:04:38 +08:00
    不可重复的(每次都是把第 4 个位置更新)用 PUT /jobs/1/nodes/4
    可以重复的(每次都在最后增加)用 POST /jobs/1/nodes
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1286 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 17:47 · PVG 01:47 · LAX 10:47 · JFK 13:47
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.