【问题标题】:JSON API .Net Core Put and Patch ExamplesJSON API .Net Core Put 和 Patch 示例
【发布时间】:2019-04-18 09:51:02
【问题描述】:

我正在使用来自 github repo {json:api}json:api 规范测试 dotnet 核心的样板库。当我从邮递员发送时,GET(有或没有查询)、POST 和 DELETE 的端点按预期工作。但是我找不到使用 PUT 或 PATCH 更改现有资源的工作示例。当我发送带有数据的补丁请求时,它给我回复“200 OK”但它在数据库中没有改变。以下是我的要求和回应。

  Request GET : http://localhost:5000/api/people -> 200 OK
  Response : [
  {
    "name": "Samuel",
    "articles": null,
    "id": 2,
    "stringId": "2"
  },
  {
    "name": "John",
    "articles": null,
    "id": 3,
    "stringId": "3"
  },
  {
    "name": "Robbin",
    "articles": null,
    "id": 4,
    "stringId": "4"
   } ]

  Request GET: http://localhost:5000/api/people/2 -> 200 OK
  Response : {
   "name": "Samuel",
   "articles": null,
   "id": 2,
   "stringId": "2" 
  }

  Request GET: http://localhost:5000/api/people/2?include=articles -> 200 OK
  Response : {
   "name": "Samuel",
   "articles": [],
   "id": 2,
   "stringId": "2" 
  }

  Request POST: http://localhost:5000/api/people -> 201 Created
  Request Body: {"name":"Samuel"}
  Response : {
   "name": "Samuel",
   "articles": null,
   "id": 2,
   "stringId": "2" 
  }

  Request DELETE: http://localhost:5000/api/people/2 -> 204 No Content

如何更新数据?

【问题讨论】:

    标签: rest .net-core json-api


    【解决方案1】:

    我在需要包含以下两个用于不同 api 调用的标头的文档中发现,并且 PATCH 的主体请求也不同。

    "Accept: application/vnd.api+json"       <--- This needs to put in header
    "Content-Type: application/vnd.api+json" <--- This also needed.
    
    Request PATCH: http://localhost:5000/api/people/3 -> 200 OK
    // Request body becomes text, anybody knows how to format to JSON?
    Request Body(Text): {
     "data": {
      "type": "people",
      "attributes": {
           "name": "John"
         }
       }
    }
    
    Response : {
          "data": {
             "attributes": {
            "name": "John"
        },
          "relationships": {
            "articles": {
                "links": {
                    "self": 
                "http://localhost:5000/api/people/3/relationships/articles",
                    "related": "http://localhost:5000/api/people/3/articles"
                }
            }
           },
              "type": "people",
              "id": "3"
           } }
    

    【讨论】:

      【解决方案2】:

      我在阅读了JSONAPI和OData的规范文档后做出了最终决定。为了更好地理解我自己的代码,我将坚持我自己的格式,我推荐 Swagger for Api Documentation。如果规范不符合我的要求,即使人们说它是标准,也没有任何意义。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-12
        • 1970-01-01
        • 1970-01-01
        • 2017-01-05
        • 2017-03-14
        • 1970-01-01
        • 2019-07-18
        • 2020-11-16
        相关资源
        最近更新 更多