duanhui1185 2015-01-08 09:36
浏览 78
已采纳

在CakePHP REST API中输入数据验证

I am developing a REST API using CakePHP. The problem is regarding the validation of data that is sent as input parameters to my API. In the CakePHP documentation they have mentioned this. But how do I implement it for a REST API?

I want that if I add a validation something like this in app/Model/Table.php:

public $validate = array(
    'email' => 'email'
); 

Then when I user makes the request myapi.com/resource?email=abc123 I want the API to respond like

status: 400

{
    "message": "Invalid Parameter",
    "url": "/resource"
}
  • 写回答

1条回答 默认 最新

  • douhe6255 2015-01-08 09:53
    关注

    Based on the documentation, in the controller you can use:

    $this->Model->set($this->request->data);
    
    if (!$this->Model->validates()) {
        $this->response->statusCode(400);
        $this->set('_serialize', array(
           'message' => 'Invalid Parameter',
           'url' => '/resource',
        ));
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?