Proper ways to create 1-1 relationship


#1

My api has a participants and an enrollments resource, where participants have 1 or 0 enrollments. This 1-to-1 is setup in the database such that enrollments table shares a primary key with the participants table. In the case where a participant already exists and the user is trying to add an enrollment to that participant, what must the api support?

Clearly this should work:

POST /participants/123/enrollment

{
    "type": "enrollments",
    "attributes": {}
}

And this should probably work too:

POST /enrollments

{
     "type": "enrollments",
     "attributes": {},
     "relationships": {
         "participant": {
             "id": "123",
             "type": "participants",
         }
     }
}

But I’m not sure about if the server needs to accept something like:

POST /enrollments

{
     "type": "enrollments",
     "id": "123",
     "attributes": {}
}

The specification is pretty clear when the id is client generated, but i’m not sure this falls into that situation.


#2

I’m pretty sure the server should accept you last example, but I think most clients would expect this to create the enrolment only, not to also link it to the participant whose id happens to be “123”.


#3

That makes sense, but in my case an enrollment cannot exist without a corresponding participant record, so creating only the enrollment would be an error. Would it make the more sense to expect the 3rd request to link to an existing participant, attempt to create a new one, or just fail?


#4

This depends on the data.

You can’t just have the third one connect to an existing participant unless you have some hard guarantee that Enrollment ID and Participant ID are equal. And if that’s the case it would imply that Enrollment and Participant are actually parts of the same resource instead of two related resources.

You could just create a Participant if one isn’t specified, but does that actually make sense? I’d guess not.

As such, failing would be the obvious answer. This would be the same as any situation where you try to create an invalid record.