Search code examples
phplaravelapiurlroutes

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


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",
}

Solution

  • 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.