【问题标题】:In a REST API, to GET a resource, should I include the resource ID in the url?在 REST API 中,要获取资源,我是否应该在 url 中包含资源 ID?
【发布时间】:2015-06-26 13:58:38
【问题描述】:

我正在尝试创建一个 REST API 来在我的数据库中创建和检索文件。我正在关注的教程使用以下方法来检索单个文件:

$app->get('/file/:file_id', 'authenticate', function($file_id) {
        global $user_id;
        $response = array();
        $db = new DbHandler();

        // fetch file
        $result = $db->getFile($file_id, $user_id);

        if ($result != NULL) {
            $response["error"] = false;
            $response["id"] = $result["id"];
            $response["file"] = $result["fileLocation"];
            $response["status"] = $result["status"];
            $response["createdAt"] = $result["created_at"];
            echoRespnse(200, $response);
        } else {
            $response["error"] = true;
            $response["message"] = "The requested resource doesn't exist";
            echoRespnse(404, $response);
        }
    });

这里他们使用 HTTP GET 方法并在 URL 中指定文件 ID,这样做可以吗,安全吗?使用 POST 并在请求正文中隐藏文件 ID 会不会更安全,或者他们不应该将文件 ID 放在 GET 请求的标头中?或者这不是我应该担心的事情?

【问题讨论】:

    标签: rest http get


    【解决方案1】:

    在 REST 中,post 方法用于创建新资源而不是获取它。 Get 方法用于获取资源,您需要指定 ID 以确定特定资源。通过 URL 传递它是一种常见的做法。您可以随机生成这样的ID,使其更难猜测。

    【讨论】:

    • 感谢您的回复
    【解决方案2】:

    正如上面所说的 Opal,ID 用于标识资源。如果您不确定是否阅读此内容 - http://blog.teamtreehouse.com/the-definitive-guide-to-get-vs-post

    【讨论】:

    • 感谢您的链接,非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-04
    • 2012-12-17
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    相关资源
    最近更新 更多