如何在 RESTful API 设计中处理错误数据类型和响应消息

How to handle error datatypes and response messages in RESTful API design

我正在构建我的第一个 RESTful API 用于练习和学习。我正在使用 RAML,并将通过 MuleSofts AnypointStudio 实现它。我真的不知道如何处理响应,尤其是错误响应。我设法弄清楚我想要哪些 HTTP 状态代码作为我的响应,但没弄清楚如何处理响应消息。

我是否需要为每个响应代码(200、201、204、404 等)定义响应数据类型和示例消息?如果我可以有一种数据类型和一种示例消息,我该如何相应地使用它们?

目前,我已经定义了一种错误类型和一种示例消息。

Error.raml

#%RAML 1.0 DataType
type: object
description: This general error structure is used throughout this API.
properties:
  code:
    type: integer
    minimum: 400
    maximum: 599
  description?:
    type: string
    default: "Bad query parameter [$size]: Invalid integer value [abc]"
    example: The server understood the request, but is refusing to fulfill it
  reasonPhrase?:
    type: string
    examples:
      example: Bad Request
      example1: Forbidden
example: !include ../examples/error_example.json

error_example.json

{
  "code": 400,
  "description": "Bad query parameter [$size]: Invalid integer value [abc]",
  "reasonPhrase": "Bad Request"
}

如您所见,我在数据类型和示例消息中都有变量。它们是由 Restlet 生成的。我还不知道怎么用,暂时就放着了。

非常感谢任何帮助和提示。

Do I need to define response datatype and example message for every response code (200, 201, 204, 404 etc.)? If I can have one datatype and one example message, how do I do use them accordingly?

不,你不知道。对于资源,您可以指定 200404 等响应(这些是最常用的)

来自文档:

resourceTypes:
  collection:
    description: Collection of available songs in Jukebox
    get:
      description: Get a list of songs based on the song title.
      responses:
        200:
          body:
            application/json:
    post:
      description: |
        Add a new song to Jukebox.
      queryParameters:
        access_token:
          description: "The access token provided by the authentication application"
          example: AABBCCDD 
          required: true
          type: string
      body:
        application/json:
          type: song
      responses:
        200:
          body:
            application/json:
              example: |
                { "message": "The song has been properly entered" }

未找到错误的资源示例:

collection-item:
  description: Entity representing a <<resourcePathName|!singularize>>
  get:
    description: |
      Get the <<resourcePathName|!singularize>>
      with <<resourcePathName|!singularize>>Id =
      {<<resourcePathName|!singularize>>Id}
    responses:
      200:
        body:
          application/json:
      404:
        body:
          application/json:
            example: |
              {"message": "<<resourcePathName|!singularize>> not found" }

有一个很棒的 blog post about this. Have a look at RAML tutorials,因为他们有很好的文档。 您还可以查看 Swagger 了解更多 "inspiration".