Http status code when creating resource but child

2019-07-23 15:30发布

问题:

consider the following resources

-Year

-Classroom

-Students

I create a new resource with next URIs related to

PUT /years/{year Es: 2108}

PUT /classrooms/{classroom code Es: ls1sa, ls2sa, ls3sa...}

POST /students

A student for a specific year belong to the classroom and the next year, if he studies, will pass to the next classroom.

I'd like to create a new resource associations year-classroom-students using the following URI

/years/{yearCode}/classrooms/{classroomCode}/students/{studentsId}

Before save new resource I check for yearCode, classroomCode, and studentId.

Which HTTP status code should I send when one of the previous resource is missing?

回答1:

Once the invalid values are sent in the URL, which is used to locate a resource in the server, in you could return 404:

6.5.4. 404 Not Found

The 404 (Not Found) status code indicates that the origin server did not find a current representation for the target resource or is not willing to disclose that one exists. [...]

On the other hand, if you want to send the parameters in the request payload, you could consider 422 to indicate that the request entity cannot be processed:

11.2. 422 Unprocessable Entity

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.


For both situations, the response payload should contain details about the error. Have a look at the RFC 7807.