简体   繁体   中英

Should I include URLs or Ids of resources in REST API response?

I am designing a REST API. There's an entity Organization which may have a parent organization and multiple child organizations.

Let's say a user does request GET /organizations/1234 . What should I respond with?

I can use URLs to these other organizations.

{
  "data": {
    "name": "Microsoft",
    "parent_organization": "http://api.myapi.asdfghj/organizations/1220",
    "child_organizations": [
      "http://api.myapi.asdfghj/organizations/1236",
      "http://api.myapi.asdfghj/organizations/1214"
    ]
  }
}

or I can use their ids

{
  "data": {
    "name": "Microsoft",
    "parent_organization": 1220,
    "child_organizations": [
      1236,
      1214
    ]
  }
}

Which one is better?

If it's the one with full URLs, how do I do document that in swagger? Do I just set that as a string, something like the following?

definitions:
  Organization:
    type: object
    properties:
      data:
        type: object
        properties:
          name:
            type: string
          parent_organization:
            type: string
            format: url
          child_organizations:
            type: array
            items:
              type: string
              format: url 

What about POST /organizations for creating a new user? Should the user specify parent and children as urls too?

I suggest you use urls rather than some ids. The advantage of having actual urls is that you can change them dynamically without worrying about the clients who depend on some base urls and then have to compute the actual urls from ids, etc.

For documentation purpose you can treat urls as strings and explain them like other params.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM