Understanding REST: Verbs, error codes, and authentication

后端 未结 10 1783
你的背包
你的背包 2020-11-22 07:39

I am looking for a way to wrap APIs around default functions in my PHP-based web applications, databases and CMSs.

I have looked around and found several \"skeleton

10条回答
  •  一向
    一向 (楼主)
    2020-11-22 08:06

    About REST return codes: it is wrong to mix HTTP protocol codes and REST results.

    However, I saw many implementations mixing them, and many developers may not agree with me.

    HTTP return codes are related to the HTTP Request itself. A REST call is done using a Hypertext Transfer Protocol request and it works at a lower level than invoked REST method itself. REST is a concept/approach, and its output is a business/logical result, while HTTP result code is a transport one.

    For example, returning "404 Not found" when you call /users/ is confuse, because it may mean:

    • URI is wrong (HTTP)
    • No users are found (REST)

    "403 Forbidden/Access Denied" may mean:

    • Special permission needed. Browsers can handle it by asking the user/password. (HTTP)
    • Wrong access permissions configured on the server. (HTTP)
    • You need to be authenticated (REST)

    And the list may continue with '500 Server error" (an Apache/Nginx HTTP thrown error or a business constraint error in REST) or other HTTP errors etc...

    From the code, it's hard to understand what was the failure reason, a HTTP (transport) failure or a REST (logical) failure.

    If the HTTP request physically was performed successfully it should always return 200 code, regardless is the record(s) found or not. Because URI resource is found and was handled by the http server. Yes, it may return an empty set. Is it possible to receive an empty web-page with 200 as http result, right?

    Instead of this you may return 200 HTTP code and simply a JSON with an empty array/object, or to use a bool result/success flag to inform about the performed operation status.

    Also, some internet providers may intercept your requests and return you a 404 http code. This does not means that your data are not found, but it's something wrong at transport level.

    From Wiki:

    In July 2004, the UK telecom provider BT Group deployed the Cleanfeed content blocking system, which returns a 404 error to any request for content identified as potentially illegal by the Internet Watch Foundation. Other ISPs return a HTTP 403 "forbidden" error in the same circumstances. The practice of employing fake 404 errors as a means to conceal censorship has also been reported in Thailand and Tunisia. In Tunisia, where censorship was severe before the 2011 revolution, people became aware of the nature of the fake 404 errors and created an imaginary character named "Ammar 404" who represents "the invisible censor".

提交回复
热议问题