首页 文章

如何设计REST API以允许返回带有元数据的文件

提问于
浏览
2

假设我正在设计REST API,我需要客户端能够获取带元数据的文件 . 设计资源/运营的好方法是什么?

想到一些想法:

  • A single resource (i.e. GET /files/), which returns a multi-part response containing both the file and a JSON/XML structure with metadata. 我觉得这不是一个很好的方法 . 例如,您不能使用客户端的Accept标头来确定他们是否需要XML或JSON元数据表示,因为响应类型在两种情况下都是多部分的 .

  • Two resources (i.e. GET /files/ and GET /files//metadata), where the first one returns the file itself and the second one a JSON/XML structure with metadata. 可以存在从元数据到文件的链接 . 但是,如何将文件链接与文件一起发送?

3 回答

  • 0

    我建议使用你提出的第二个想法 . 这是大多数主要网络驱动器(Box,Dropbox,Google Drive等)使用的策略 . 它们通常具有明显不同的URL,因为它们将内容和元数据存储在不同的位置 .

    您可以使用指向元数据的链接向文件响应添加链接标头 . 链接头在RFC 5988中描述 . 当前注册的链接关系集是here . 关闭袖口,似乎 describedBy 关系在这里是合适的 .

  • 3

    我在以下API设计方面取得了成功 . 这与您建议的略有不同,主要资源只包含其组件的链接 .

    POST /file
    Request
      <bytes of file>
    Response
      Location: /file/17
      {
        "id": 17
      }
    
    GET /file/17
      {
        "data": "/file/data/17",
        "metadata": "/file/metadata/17"
      }
    
    GET /file/data/17
      <bytes of file>
    
    GET /file/metadata/17
      {
        "type": "image",
        "format": "png"
      }
    
    DELETE /file/17
    
  • 4

    您的第一个选项根本不是一个好的选择,因为它违反了以下REST约束 .

    Manipulation of resources through these representations Uniform interface 原则 .

    当客户端持有资源的表示(包括附加的任何元数据)时,它具有足够的信息来修改或删除资源 .

    如果你刹车的话 . 您的URL不会被视为RESTful .

    Wiki关于它 .

相关问题