简体   繁体   中英

Signaling about 404 error in REST API

What's the idiomatic way to signal the caller about an error in API, in particular, "Not found" error? Suppose, I have an url /api/vi1/check/123 . What should I return in case

  1. There is no such a record with id = 123? 404 error (Http status 404)?

    status: 404 (http); data: { }

  2. Or should I return OK status (Http status 200) and json with the internal status

    status: 200 (http); data: { status: 404, msg: "Not found"}?

  3. And (related to 1 ) what should I return if there is no such an url ? Also Http 404 status?

Yes, I've seen the best practice videos and read the articles about REST APIs but this question wasn't answered clearly in those.

REST is about using HTTP's semantics. It also applies to error codes. You should use the 404 status code, and eventually a more descriptive error message in the body.

Yes you should return a simple 404, no more no less. (Maybe a message to go with that...) That is indicating that the resource you are looking for is not there which is good practice in REST.

It is also good practise not to provide any body here (like an internal status code, or message). If you really need a message in such a case (404 or 500 on an error) you can do that with an additional HTTP header field (eg X-Message: Database not available). But a 404 with empty response body is really sufficient here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM