JSON API .Net核心放置和修补示例

时间:2018-11-15 10:09:33

标签: rest .net-core json-api

我正在测试来自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

如何更新数据?

2 个答案:

答案 0 :(得分: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"
       } }

答案 1 :(得分:1)

阅读JSONAPI和OData的规范文档后,我做出了最终决定。我将坚持自己的格式,以便更好地理解我自己的代码,并且我建议使用Swagger for Api Documentation。即使人们说这是标准,该规范是否仍无法满足我的要求,这是没有道理的。