5

在 Stack Overflow 上针对 RESTful URL 设计提出了许多问题

仅举几例...

分层 URL 设计: 分层 RESTful URL 设计

了解 REST:动词、错误代码和身份验证:了解 REST:动词、错误代码和身份验证

所以我很清楚Restful URL Design。但是,对于不是单页应用程序 (SPA) 的传统网站的浏览器 URL 设计怎么样。

出于本示例的目的,假设我们有一个图书数据库。让我们进一步假设我们创建了 2 个传统的 HTML 站点。

  1. 用于显示所有书籍的 HTML 表格
  2. 用于显示一本书的 HTML 表单(空白或预先填写书籍详细信息)

现在我们希望我们网站的用户可以使用它进行 CRUD 操作。那么下面的 URL 设计怎么样:

GET /book/show/all        // HTML Table
GET /book/show/{id}       // HTML Form pre-filled
GET /book/new             // HTML Form blank
POST /book/new            // Submit HTML Form
POST /book/update/{id}    // Submit updated HTML Form
POST /book/delete/{id}    // A Link/Button with POST ability (no JS needed)

问题:

最佳实践浏览器 URL 设计

我是否遵循浏览器中 URL 设计的最佳实践(我不是在这里谈论 REST)?还关于 SEO、书签和短 URL 设计?我在想类似的东西:/resource/action/ ...

仅 GET 和 POST URL 设计

除非有人使用 JavaScript,否则浏览器只能进行 GET 和 POST。考虑到上面的 URL 设计,引入 JavaScript 并发出 PUT 和 DELETE 请求来更新和删除资源是否更明智?或者我应该只使用 GET 和 POST 吗?

干杯

4

1 回答 1

6

而不是 CRUD(创建-读取-更新-删除),我更喜欢首字母缩写词 (D)AREL(显示、添加、删除、编辑、列表)—— (D) 是无声的 ;-)

虽然并非所有 RESTful API 设计选择对于基于浏览器的 crud 应用程序都有意义,但我们可以借鉴其中的大部分内容,例如:

GET  /books                -- html table listing all books (alternatively /books/list to go with the DAREL acronym)
GET  /books/add            -- display a form for adding a new book
POST /books/add            -- adds a new book and redirects to /book/1 (where 1 is a new book id)

我个人更喜欢对集合使用复数名词,对项目使用单数名词,所以..

GET  /book/1               -- display book 1 info (e.g. a customer view)
GET  /book/1/edit          -- display a form to edit /book/1
POST /book/1/edit          -- updates /book/1 and redirects to /book/1
GET  /book/1/remove        -- maybe/probably optional
POST /book/1/remove        -- normally /book/1/edit will have a delete button that handles "are you sure..?" and posts here, redirects to /books

uri 方案是/resource/unique-identifier/action. (D) / display 动作对于给定的资源 uri 是静默/默认的。

如果您想模拟一本书可以有多个作者,这也适用:

GET  /book/1/authors       -- list all authors for /book/1
GET  /book/1/authors/add   -- add author form
GET  /book/1/author/1
GET  /book/1/author/1/edit
// etc.

尽管您可能需要为作者提供单独/附加的 url 层次结构:

GET  /authors
GET  /authors/add
GET  /author/1
// etc.

同样,作者写的书:

GET  /author/1/books
// etc.

大多数现代网络应用程序使用 ajax 调用子资源,所以在这里你也可以使用纯 RESTful api:

GET    /api/book/1/authors     -- returns list of all authors for /book/1
POST   /api/book/1/authors     -- create a new author, returns the new author uri, e.g. /api/author/1
GET    /api/author/1           -- get /author/1 info according to MIME type etc.
PUT    /api/author/1           -- update /author/1
DELETE /api/author/1           -- delete the /author/1 resource
DELETE /api/book/1/author/1    -- delete author/1 from /book/1? (or maybe this is covered by PUT /api/author/1 ?)

原始 url-scheme 的翻译非常机械

/resource/unique-id/action -> http-verb /resource/unique-id

其中动作 = http-动词

display = GET (on a singular resource)
add = POST
remove = DELETE
edit = PUT
list = GET (on a plural/collection resource)
于 2019-05-07T07:39:50.097 回答