REST best practice for naming nested resources

2019-08-23 13:24发布

问题:

Currently I have the following resource:

/api/user/12

returns information about user with id=12

/api/user/12/trips

returns a list of trips made by user 12 and their information

However I consider /trip/ a separate resource, so this would continue like this:

/api/trip/5

returns information about trip with id=5

Is this a good way to do this?

回答1:

You should always use plural to name resources:

/api/users

Meaning: all users (collection).

/api/users/12

Meaning: user 12.

For nested resources related to a given resource, you can do:

/api/users/12/trips

Meaning: all trips for user 12.

But, you still can describe a specific trip using this URI:

/api/trips/5

Meaning: trip 5.



回答2:

The best practice is to use the path to the domains.

To show a certain user:

/api/user/{username}

To show all the users:

/api/user

Use query for filtering all the users.

/api/user?region=Italy

Here a nice article: http://developer.immobilienscout24.de/wiki/Path_and_Query_Parameters



标签: api rest