V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
coolair
V2EX  ›  API

关于 API 设计问题,请大家指点指点

  •  
  •   coolair · 124 天前 · 960 次点击
    这是一个创建于 124 天前的主题,其中的信息可能已经有所发展或是发生改变。
    我用的 DRF 。

    在设计时,比如: http://localhost/tasks

    如果想要一个获取用户 tasks 的接口:
    当前用户: http://localhost/users/me/tasks
    其他用户: http://localhost/users/{id}/tasks

    如果把这个接口放在 user view 里面实现,就无法复用 task view 里面的 filter ,如果放在 task view 里面实现,重写 url path ,感觉 url 不一致,容易造成误解。
    7 条回复    2023-12-26 18:22:37 +08:00
    luckrnx09
        1
    luckrnx09  
       123 天前 via iPhone   ❤️ 1
    前端如果能拿到当前用户 id 的话,我觉得 http://localhost/users/{id}/tasks 一个接口就够了。
    orangie
        2
    orangie  
       123 天前   ❤️ 1
    应该是 /tasks?userId=xxx 这样设计,查询的主体是 task ,task 并不是 user 的一部分,反过来 user 也不是 task 的一部分,而是查询条件,所以应该用 query ,这样既复用 task view 里面的 filter ,url 也完全没有问题。
    coolair
        3
    coolair  
    OP
       123 天前
    @luckrnx09 #1 这样的话,就没办法获取到所有的 tasks 了。
    coolair
        4
    coolair  
    OP
       123 天前
    @orangie #2 这样的话,如果想获取 task 详情,/tasks/{id} 这样,再传 userId=xxx 就不太好了,如果使用 /users/{user_id}/tasks/{task_id} 就很清晰了。
    KiepieDd
        5
    KiepieDd  
       123 天前
    http://localhost/users/{id}/tasks 留着一个就够了,http://localhost/users/me/tasks 这个可以不用,因为获取当前用户的可以通过 session 获取 id
    orangie
        6
    orangie  
       123 天前
    @coolair 获取 task 详情,/tasks/{id} 这样就应该是完全不需要传 userId=xxx 了吧,难道 task 和 user 是多对多的关系?我理解 task 和 user 是多对一的关系。如果居然是多对多的关系,也就是同一个 task 对不同用户看起来居然有差别,那么传 userId=xxx 也是必然的。用路径表示实体和属性的关系,用 query 表示关联关系比较清晰。
    qiaofanxing
        7
    qiaofanxing  
       123 天前
    task 和用户是多对多的关系吗?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3023 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 286ms · UTC 13:35 · PVG 21:35 · LAX 06:35 · JFK 09:35
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.