当前位置:首页 > Windows程序 > 正文

HTTP methods 与 RESTful API

2024-03-31 Windows程序

Note GET, primarily used to select resources. Other options for an API method include: POST, primarily used to create child resources. PUT, primarily used to update existing resources (and, although not recommended, can be used to create child resources). DELETE, used to delete resources. PATCH, used to update resources. HEAD, primarily used in testing scenarios. It is the same as GET but does not return the resource representation. OPTIONS, which can be used by callers to get information about available communication options for the target service. The method created is not yet integrated with the back end. The next step sets this up.

目录:

RESTful 是什么

JSON-server (提供 RESTful API 接口 + JSON 返回数据)

如何选择 REST 方法

HTTP verbs / method (安全 | 幂等)

HTTP POST V.S. PUT

REST POST | PUT | PATCH

HTTP verbs 推荐返回的状态码

技术图片

TOP10 HTTP Status Code in REST

200 OK 201 Created 204 No Content

304 Not Modified

400 Bad Request 401 Unauthorized 403 Forbidden 404 Not Found 409 Conflict

500 Internal Server Error

水很深,现在还理解不了

JSON-Server

JSON-Server 是一款前端测试工具,可提供 REST API + JSON 服务。

来看一组 JSON-Server 提供的 RESTful API 接口:

GET /posts //获取posts下的所有资源 GET /posts/1 //获取posts下id为1的资源 GET /posts?title=json-server&author=typicode //获取posts下title=json-server&author=typicode的资源 POST /posts //posts添加操作,非幂等,每次都添加新的,除非已存在!

创建资源成功时,应当返回201 Created而不是200 OK。同时,

需要在HTTP response headers的location节中返回所创建的新资源对应的URL,

同时返回该资源的内容。 PUT /posts/1 //对posts下id为1的资源进行修改操作:完全替换,或者不存在则新增。

官方的定义,使用PUT方法,,意味着或者不存在该资源,则创建一个新的资源;

或者存在该资源,使用新的资源完整替换原有资源。

无论哪一种,多次操作后得到的系统状态的结果是完全一致的,因而符合幂等性。

资源的标识在方法中,通过参数id独立传递,ProductInput并不包含id属性。

在更新前,需要判断id对应的资源是否存在,然后进行进一步的操作。 PATCH /posts/1 //对posts下id为1的资源进行修改操作:局部更新 DELETE /posts/1 //对posts下id为1的资源进行删除操作

有这两个明显的特点:

每个 URI 代表一种资源。用名词表示。

HTTP method 表示对资源进行了哪种类型的操作。

使用时需注意:

安全|幂等 是由 HTTP 标准定义的契约:开发者在实现 RESTful API 时必须遵守。

如果一个操作没有以幂等的方式实现,那么即使它是通过 GET 方法调用的,它也不会自动变成 幂等的/ 安全的。

当使用 HTTP 构建 RESTful 程序时,对HTTP method 的实现应该满足其安全性和幂等性,来使 client 和中间件能自由地按契约优化,并增强用户体验。

e.g. 浏览器并不确切知道某个特定的 form 用途,但如果这个 form 是通过 HTTP GET 提交的,浏览器就会知道当出现网络异常的时候,它可以安全的、自动再次尝试提交。 而通过 HTTP POST 提交的 form,如果浏览器不先向用户确认就重复提交,会是不安全的。

技术图片

RESTful 下的 post put patch

put

幂等:对同一URI进行多次PUT的副作用和一次PUT是相同的。

PUT 所对应的URI是要创建或更新的资源本身。比如:PUT xx/articles/4231 的语义是创建或更新ID为4231的帖子。

patch

非幂等 e.g. patch 可以对资源进行逻辑判断增量修改,如每次加3,那么执行多次,就会造成额外影响。

对已有资源的局部更新(而不用指定整个资源)。

PUT

PUT puts a file or resource at a specific URI, and exactly at that URI.

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/43476.html

Jm-杰米博客Jamie
草根站长的技术交流乐园!IT不会不要紧快来好好学习吧!
  • 20786文章总数
  • 7494595访问次数
  • 建站天数
  • 友情链接