mercredi 9 juin 2021

RESTful API Design: How to handle POST for entities that must verify the existence of FKs before saving the main record? 404 or 422 or?

Question

I want to know what are the best practices (if any) when handling a restful POST where the PARENT entity has CHILD entities that must exist before saving the main entity.

My Thoughts

My initial thoughts are 404s are for when the PARENT entity is NOT FOUND. However, when the CHILD entities are not found a 422 should be returned.

Why a 422? Well IMO a 422 is the server saying, "Hey I found the main entity you were after. I know what you are trying to do (create this parent entity). However, I cannot find all the information I need to finish creating the PARENT entity."

Case Study

Below I've created some sample data and schemas to help illustrate the question.

Case 1

Sending the following should succeed with 200 if "Spaghetti" and "BestBuy" exist in the foreign tables.

POST /people
{
    firstName: "John",
    lastName: "Doe",
    favoriteFoodName: "Spaghetti",
    favoriteStoreName: "BestBuy"
}
Case 2

Sending the following should succeed with 422 if either "Sushi" or "Old Navy" don't exist in the foreign tables.

POST /people
{
    firstName: "Jane",
    lastName: "Doe",
    favoriteFoodName: "Sushi",
    favoriteStoreName: "Old Navy"
}

Data Models

enter image description here

Aucun commentaire:

Enregistrer un commentaire