处理REST API中的公共和内部ID的最佳做法,使用Laravel中的UUID和slug列

huangapple go评论65阅读模式
英文:

Best practice for handling public and internal IDs in REST APIs using UUID and slug columns in Laravel

问题

我有一个包含经典自增ID和企业名称的表。为了避免向客户端暴露企业ID,我想使用UUID。到目前为止,一切都很好。唯一的问题是,为了从URL中调用它,最好使用更用户友好的格式,如"api/businesses/my-business",而不是"api/businesses/10b940f2-5f8c-42ac-9c35-b6d0de45995b"。因此,如果我在表中添加一个"slug"列用于GET请求,同时在数据更新时使用UUID,这是否被视为最佳做法?

在我的情况下,我需要在报价表中创建一条记录,因此PATCH请求将如下:

PATCH /api/quotes/4dc93692-0ad9-4131-94fe-b4afec88d037

{
    "business_uuid": "10b940f2-5f8c-42ac-9c35-b6d0de45995b",
    "object": "我的报价对象",
    "another_column": "你好",
}
英文:

I have a table that contains a classic auto-incrementing ID and the name of the business. To avoid exposing the business ID to the client, I want to use a UUID. So far, so good. The only thing is that for calling it from the URL, it may be better to have a more user-friendly format like "api/businesses/my-business" instead of "api/businesses/10b940f2-5f8c-42ac-9c35-b6d0de45995b". Therefore, if I add a "slug" column to the table to use for GET requests, while using the UUID for data updates, would this be considered a best practice?

In my case, I need to create a record in a quotes table, and therefore the PATCH will be:

PATCH /api/quotes/4dc93692-0ad9-4131-94fe-b4afec88d037

{
    "business_uuid": "10b940f2-5f8c-42ac-9c35-b6d0de45995b",
    "object": "My quote object",
    "another_column": "Hello",
}

答案1

得分: 2

如果你的数据库表结构包含 iduuidslug,请考虑以下:

  1. 仅在后端内部使用 id
  2. 在处理 REST API(CRUD)资源时,使用 uuid
  3. 当你想在某个地方处理资源,并且更容易让人阅读、识别和理解数据时,请使用 slug。不要忘记 slug 必须是唯一的。但对于服务之间的基本CRUD操作,我仍然建议继续使用 uuid

我还建议查看 Laravel 文档中关于Laravel资源的内容,它可以帮助你准备API数据,以及slugify帮助函数来处理你的某个数据字段。

英文:

If your database table structure contains id, uuid, slug, consider following:

  1. Use id internally within backend only.
  2. Use uuid when processing resources with REST API (CRUD).
  3. Use slug when you want to process resources somewhere where its more easier for human to read/identify/understand data. Don't forget that slug must be unique. But for basic CRUD operations between services I would still recommend to keep using uuid.

I would also recommend to checkout Laravel docs regarding Laravel Resources which can help you to prepare data for API, and slugify helper function to process one of your data fields.

huangapple
  • 本文由 发表于 2023年2月18日 20:57:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75493488.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定