DominikS
DominikS

Reputation: 381

Foreign key constraint in REST API

I'm designing RESTful API for trip planner application and don't know how to enforce foreign key constraint on resource creation. I have two resources: Trip and User. Trip resource looks like this:

{
  "id": 1,
  //some other attributes
  "tripParticipants":[ 
    {
      "id": 1
    }
   ]
}

where tripParticipants is collection of User ids. TripParticipants should only contain created Users (by created I mean stored in database).

I have trouble with endpoint POST /trips/{id}/tripParticipants to add elements to the collection. What should I return when User with given id doesn't exist in my database? Returning HTTP 404 status code for POST operation looks weird. Does REST standard defines some solutions to this use case?

Upvotes: 6

Views: 2118

Answers (2)

Opal
Opal

Reputation: 84824

There are two HTTP status codes that can be used in this situation:

Both are correct for your scenario. Personally I'd go with 422.

Upvotes: 7

Martin
Martin

Reputation: 16302

For Rest you follow the Http standard status codes, so 404 is the appropriate code for Rest.

These are the status codes you could be using https://www.restapitutorial.com/httpstatuscodes.html

Upvotes: -1

Related Questions