Restful API URL 获取不同文件类型格式的 json 数据

Restful API URL to get json data for different file type format

我正在构建 restful API URLs 来获取产品数据。所以我有,

POST /products
GET /products
GET /products/{:id}
DELETE /products/{:id}

其中一项要求是提供端点以获取 JSON 中的产品数据,以便导出为不同的文件格式、CSV 和 PDF。它将被其他服务(导出服务)调用。

响应示例:

PDF

{ 
  products_pdf: {
     title: 'Products',
     sub_title: 'as per May 20 2018',
     products: [
       {
          name: 'product A', 
       },
       {
          name: 'product B', 
       }
     ]
  }
}

对于 CSV,响应比 PDF 更简单。根据要求,不能在一个响应中同时提供两者。

{
  products_csv: [
    {
      name: 'product A',
    },
    {
      name: 'product B'
    } 
  ]
}

它的正确 restful URL 端点是什么?

我在想

GET /products/exports/{:file_format}
GET /products/exports/csv
GET /products/exports/pdf

老 Google 财经 API 提供了多种格式的历史数据。这些格式可以通过查询字符串参数 output 的不同参数来请求。

例如:

http://www.google.com/finance/historical?q=GOOGL&output=csv

您可以设计端点来处理参数,return 响应的格式根据指定的输出参数。如果提供的输出类型无效,select 默认的 choosing/which 最适合您的特定数据。

对我来说,数据格式是可选,因此不应该规定资源端点。对我来说最合乎逻辑的解决方案是使用默认格式并使用查询字符串参数来覆盖例如

GET /products?format={pdf|csv}

IMO,exports 一词出现在 URL 中看起来不太好。端点可以在 url 扩展名中具有响应类型。

例如:

/products.json
/products.xml
/products.pdf
/products.csv

如果你不喜欢这个模式,你可以很好地使用Accept HTTP header