使用RAML规范的REST API:如何在响应中指定总页数

时间:2018-11-12 13:04:14

标签: rest api raml

我不确定分页方面应该如何设计REST API。

这是我的例子:

#%RAML 1.0
title: Test Api Documentation
description: Test Api Documentation
baseUri: https://localhost/
version: v0.1
protocols: [ HTTPS ]
mediaType: [ application/json ]
documentation:
  - title: Test API for REST Client
    content:
      "Test API for REST Client."
types:
  Thing:
    type: object
    properties:
      name: string
      age: number
      color: string
  Things:
    type: object
    properties:
      things?: Thing[]
      totalPages?:
        type: integer
        format: int64
/things:
  get:
    headers:
      Cookie:
        type: string
    responses:
      '200':
        description: OK
        body:
          application/json:
            type: Things
      '401':
        description: Unauthorized
      '404':
        description: Not Found
    queryParameters:
      page:
        description: page
        required: false
        type: integer
        format: int32
      pageSize:
        description: pageSize
        required: false
        type: integer
        format: int32

有这种包装类型“ Things”,可以为响应添加totalpages属性。

这是正确的方法吗?

我还读到可以使用自定义的http标头(x-total-pages或类似的内容)。

我实际上不喜欢在API中包含所有包装类型... 有人知道这是什么标准吗?

非常感谢您的回答。 塞尔吉奥

1 个答案:

答案 0 :(得分:2)

您可以将所有分页的特征封装到trait中,并使用is在所有可分页资源中使用它。由于可分页资源通常是GET / collectionresource,因此您还可以为200个paginated响应的响应头X-TOTAL-PAGES添加一个特征。

示例:

#%RAML 1.0
baseUri: https://mocksvc.qax.mulesoft.com/mocks/8ab3d909-11e0-4f1d-aaef-bef029b83fbf
title: paginated api
mediaType: application/json
protocols: [ HTTP ]
traits:
  paginated:
      queryParameters:
        page:
          description: page
          required: false
          type: integer
          format: int32
        pageSize:
          description: pageSize
          required: false
          type: integer
          format: int32    
      responses:
        200:
          headers:
            x-total-pages:  
types:
  Thing:
    type: object
    properties:
      name: string
      age: number
      color: string
  Things:
    type: object
    properties:
      things?: Thing[]

/things:
  get:
    is: [ paginated ]
    responses:
      '200':
        description: OK
        body:
          application/json:
            type: Things
      '401':
        description: Unauthorized
      '404':
        description: Not Found 

raml2html output