REST best practice for naming nested resources

2019-08-23 13:23发布

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?

标签: api rest
2条回答
叼着烟拽天下
2楼-- · 2019-08-23 13:54

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

查看更多
闹够了就滚
3楼-- · 2019-08-23 14:10

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.

查看更多
登录 后发表回答