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"
}

图片转代码服务由CSDN问答提供 功能建议

我正在使用CakePHP开发REST API。 问题是关于作为输入参数发送到我的API的数据的验证。 在 CakePHP文档中,他们提到了这个。 但是如何为REST API实现它呢?

如果我在 app / Model / Table.php 中添加类似的验证,我希望如此:

 <  code> public $ validate = array(
'email'=&gt;'email'
);  
   
 
 

然后,当我的用户发出请求 myapi.com/resource?email=abc123 时,我希望API能够像

status:400

  {
“message”:“无效参数”,
“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',
        ));
    }
    
    点赞 打赏 评论

相关推荐 更多相似问题