在API平台中,可以使用各种工具来验证参数。以下是使用PHP实现API参数验证的示例代码:
首先,您需要在API控制器中定义需要验证的参数,例如:
/**
* @ApiResource(
* collectionOperations={"get", "post"},
* itemOperations={"get", "put", "delete"},
* attributes={
* "input"={
* "class"=User::class,
* "validation_groups"={"Default", "create"}
* }
* }
* )
*/
class UserController {
// ...
}
在此示例中,我们在User实体类中定义了参数验证组“create”。现在我们需要在API平台中添加参数验证器。可以使用Symfony的内置验证器。
/**
* @ApiResource(
* collectionOperations={"get", "post"},
* itemOperations={"get", "put", "delete"},
* attributes={
* "input"={
* "class"=User::class,
* "validation_groups"={"Default", "create"},
* "deserialize_validation_groups"={"Default", "create", "update"}
* }
* }
* )
*/
class UserController {
// ...
}
在此示例中,我们添加了deserialize_validation_groups属性。这将使API平台使用验证组“update”来验证PUT和PATCH请求的参数。
接下来,我们需要在User实体类中添加验证器注释。例如:
use Symfony\Component\Validator\Constraints as Assert;
class User {
/**
* @var string
*
* @Assert\NotBlank(groups={"create"})
* @Assert\Length(min=3, max=255, groups={"create", "update"})
*/
private $name;
// ...
}
在此示例中,我们添加了两个验证器:NotBlank和Length。NotBlank验证器将确保参数不为空,而Length验证器将确保参数为3到255个字符长。
现在,如果在POST请求中未提供name参数,则API平台会返回以下响应:
{
"code": 400,
"message": "Validation failed