英文:
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
如果你的数据库表结构包含 id
、uuid
和 slug
,请考虑以下:
- 仅在后端内部使用
id
。 - 在处理 REST API(CRUD)资源时,使用
uuid
。 - 当你想在某个地方处理资源,并且更容易让人阅读、识别和理解数据时,请使用
slug
。不要忘记slug
必须是唯一的。但对于服务之间的基本CRUD操作,我仍然建议继续使用uuid
。
我还建议查看 Laravel 文档中关于Laravel资源的内容,它可以帮助你准备API数据,以及slugify帮助函数来处理你的某个数据字段。
英文:
If your database table structure contains id
, uuid
, slug
, consider following:
- Use
id
internally within backend only. - Use
uuid
when processing resources with REST API (CRUD). - Use
slug
when you want to process resources somewhere where its more easier for human to read/identify/understand data. Don't forget thatslug
must be unique. But for basic CRUD operations between services I would still recommend to keep usinguuid
.
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论