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

如何在RESTful API设计中处理错误数据类型和响应消息,rest,error-handling,api-design,raml,Rest,Error Handling,Api Design,Raml,我正在为练习和学习构建我的第一个RESTful API。我正在使用RAML,并将通过MuleSofts AnypointStudio实现它。我真的不知道如何处理响应,尤其是错误响应。我设法找出了我想要的响应HTTP状态码,但没有设法找出如何处理响应消息 我是否需要为每个响应代码(200、201、204、404等)定义响应数据类型和示例消息?如果我可以有一个数据类型和一个示例消息,我如何相应地使用它们 目前,我已经定义了一种错误类型和一条示例消息 Error.raml #%RAML 1.0 Dat

我正在为练习和学习构建我的第一个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
错误\u example.json

{
  "code": 400,
  "description": "Bad query parameter [$size]: Invalid integer value [abc]",
  "reasonPhrase": "Bad Request"
}
如您所见,我在数据类型和示例消息中都有变量。它们是由Restlet生成的。我还不知道如何使用它们,所以我暂时就离开了它们

非常感谢任何帮助和提示

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

不,你没有。对于资源,您可以指定响应,例如
200
404
(这些是最常用的)

从文档中:

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" }
收集项目:
描述:表示
获取:
说明:|
得到
带身份证=
{Id}
响应:
200:
正文:
应用程序/json:
404:
正文:
应用程序/json:
例如:|
{“消息”:“未找到”}
这件事有一个很好的解释。看一看,因为他们有很好的文档。
你也可以看看更多的“灵感”。

这正是我一直在寻找的。我希望有一种方法可以为错误消息创建一个数据类型或模式(带变量?),并在每个错误响应中相应地重复使用它。但这必须要做,谢谢。如果可以的话,我想等待更多的答案。如果没有更多的答案,我会在几天后将其标记为已回答