简体   繁体   中英

Are these REST HTTP response codes right, and what about the Content-Type?

I'm writing a controller helper that sets the proper response headers for my REST controller action. It's pasted below and should be simplified enough for those who aren't familiar with Zend Framework to understand what I'm doing.

My question is: Are these codes correct for their respective responses, and in the case of "access denied" do I use a 401 or 403?

Also, in case of responding with an error, I understand I should be placing a message in the response body, but should I set the "Content-Type" to "text/plain"?

<?php

class App_Controller_Helper_RestResponse extends Zend_Controller_Action_Helper_Abstract
{
    public function denied()
    {
        // 403 or 401?
    }

    public function notFound()
    {
        // 404
    }

    public function created()
    {
        // 201
    }

    public function deleted()
    {
        // 204
    }


    public function redirect()
    {
        // 301
        // new url
    }

    public function malformed()
    {
        // 400
    }

    public function gone()
    {
        // 410
    }


}

Those look pretty good to me, I tend to use 200 for deleted, but I don't see anything wrong with using 204 if you're never going to send back any entity when you process a delete. Regarding 401 vs 403, they're tricky because they are named poorly. 401 says "unauthorized" but the requirement to send a WWW-Authenticate header suggests to me that it should really be used when the request isn't "Authenticated". 401 says: "I can't let you do that because I'm not satisfied I know enough about you. 403 on the other conveys the resource is "Forbidden", just another way of saying "not authorized" only in this case, there is no effort made to get the user better authenticated than they already are. Use 403 when you need to express: "I know who you are, and I don't care, I'm not going to let you do that."

Otherwise those look good, though you may want to consider 302, 303 and 307 as additional redirects depending on why you are doing the redirect. Have an additional look at http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html and let me know if you need some more insight on the redirect headers.

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