简体   繁体   中英

REST api resource dependencies

I have this data management panel of IP addresses, which belong to organization and have users responsible for it.

Now I have the route /api/ip and /api/ip/{id} to get all or specific IP. The format of one resource is:

{
    "ip": "200.0.0.0",
    "mask": 32,
    "broadcast": "200.0.0.1"
}

Now when I choose the IP, I want to show IP information, also the organization information it belongs to and the users, that are responsible for it, information in one page.

Is it good idea to return the following data format, while requiring /api/ip/{id} :

{
    "ip": "200.0.0.0",
    "mask": 32,
    "broadcast": "200.0.0.1",
    "organization": { /* organization data */ },
    "users": { /* users information */ }
}

This way I get all the information I need in one request, but is it still RESTful API?

Or should I make 2 more api routes like /api/ip/{id}/organization and /api/ip/{id}/users and get all the data I need in 3 separate requests?

If not, what would be the appropriate way of doing this?

I would do the last one, using Hateoas, which allows you to link between the resources. There is a really great bundle for that called the BazingaHateoasBundle . The result will then be something like:

/api/ip/127.0.0.1

{
    "ip": "200.0.0.0",
    "mask": 32,
    "broadcast": "200.0.0.1",
    "_links": {
        "organization": "/api/ip/127.0.0.1/organization",
        "users": "/api/ip/127.0.0.1/users"
    }
}

It is perfectly okay to have nested resources. You can expand them the way you showed, or you can collapse them by adding links (with the proper link relation or RDF metadata). I suggest you to use a standard or at least documented hypermedia type, eg JSON-LD + Hydra, or HAL+JSON.

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