I'm creating a REST API for my application, and I have a doubt about how to design my API, following REST principles. I'm using PHP and Lumen, but I guess it's more a design doubt than a technical one.
Consider I have two entities:
Company:
- id
- name
User:
- id
- name
- email
- company_id
Each Company
must have one or more User
's, and I'd like to assert that rule in my API. As far as I've understood REST specifications, I should create one endpoint for each entity, so the API client should make a POST to http:\\myserver\api\company
to include a company, and after that make another POST to http:\\myserver\api\company\{id}\users
to include a User
in the new Company
. The problem with that approach is that the client could only create a Company
and leave it without User
's.
In a non-rest API, I could create a method called createNewUser
, which would receive the user's data together with Company
data, and this method would ensure that both entities are created.
How could I achieve that in a REST API?
CodePudding user response:
I have a doubt about how to design my API, following REST principles.
Part of the problem here could be the confusing messages you are getting about "REST principles".
Consider how you might do this on the web. You want somebody to give you both user data and company data. So you would create a web page with a form; some of the form controls would be designed to collect user data, some would be designed to collect company data. When the form is submitted, the browser would copy the information from the forms input controls into an application/x-www-form-urlencoded
request body, and POST it to the target URI specified in the metadata of the form. Ta-da.
That's REST.
Is that the only answer that's REST? No. Equally RESTful would be to have clients write the user and company data into a local document, and then save a copy of that document on the web server. Or to download a document from the web server, edit the user and company data into the local copy, then save the revised document on the server. Or to send a patch document describing the edits to the web server, and allow the server to compute the changes to its own copy of the document.
All of these are fine.
as I've understood REST specifications, I should create one endpoint for each entity,
This is where you are getting derailed (not your fault, the literature sucks)
- REST doesn't have endpoints, it has resources
- HTTP requests target resources, not entities
- "different entity therefore different resource" is not a constraint that comes from REST.
Fine grained resources work well in some cases (in particular they are a good fit for copying information into an anemic data model), but they aren't universal. In a context where fine grained resources don't work well... design your resource model differently.