Say I have a User resource which must always be attached to another type of resource, a Business.
When creating a new User, is it OK to have the POST endpoint use a query parameter to specify the Business to use?
For example:
POST /users?business=123
{"firstName": "John", "lastName": "Smith"}
-
Why not POST /users { "user": {"firstName": "John", "lastName": "Smith"}, "business": 123 } ?Dan Pichelman– Dan Pichelman2016年09月01日 15:02:42 +00:00Commented Sep 1, 2016 at 15:02
-
1You haven't specified an API paradigm (e.g. REST) you're trying to follow, so yes, it's okay if it follows HTTP (which it does).Evan– Evan2016年09月01日 15:56:12 +00:00Commented Sep 1, 2016 at 15:56
1 Answer 1
Yes, you can; there is nothing about HTTP that imposes a particular API structure. However, I would suggest you give the subject some thought.
API modelling is all about understanding your domain model; it depends on the relationship between business
and user
and the relative significance of these entities.
Here are my thoughts as to your main options; I cannot answer this question for you, but this will hopefully help you approach the problem in the right way.
One-to-Many
- A business may contain many users
- A user may only be linked to one business
If the users are treated as properties or components of a business, then make the users a child-object of the business.
POST /businesses/123/users
{"firstName": "John", "lastName": "Smith"}
If the users are viewed as distinct entities that are only linked to a business, then simply link the user to the business.
POST /users
{ "user": {"firstName": "John", "lastName": "Smith"}, "business": 123 }
Many-to-Many
- A business may contain many users
- A user may be linked to many businesses
You could make the link to businesses a property of the user.
POST /users
{ "user": {"firstName": "John", "lastName": "Smith"}, "businesses": [123, 789] }
Or, if the link to a business has substantial significance to your domain model, you could make a whole new entity that represents employment.
POST /users
{ "user": {"firstName": "John", "lastName": "Smith"} }
POST /employment
{ "user": 345, "business": 123, "commenced": "2016-09-01", "terminated": false }