如何在RESTful API中为POST方法设置正确的JSON响应


How to set proper JSON response for POST method in RESTful API from FOSRestBundle?

我正在为RESTful API制作POST方法。正如你可能注意到的,这个API是建立在FOSRestBundle和NelmioApiDoc之上的。当文件未上传或缺少rid参数并使用适当的JSON响应时,我无法验证。这就是我正在做的:

/**
 * Set and upload avatar for reps.
 *
 * @param ParamFetcher $paramFetcher
 * @param Request $request
 *
 * @ApiDoc(
 *      resource = true,
 *      https = true,
 *      description = "Set and upload avatar for reps.",
 *      statusCodes = {
 *          200 = "Returned when successful",
 *          400 = "Returned when errors"
 *      }
 * )
 *
 * @RequestParam(name="rid", nullable=false, requirements="'d+", description="The ID of the representative")
 * @RequestParam(name="avatar", nullable=false, description="The avatar file")
 *
 * @return View
 */
public function postRepsAvatarAction(ParamFetcher $paramFetcher, Request $request)
{
    $view = View::create();
    $uploadedFile = $request->files;
    // this is not working I never get that error if I not upload any file
    if (empty($uploadedFile)) {
        $view->setData(array('error' => 'invalid or missing parameter'))->setStatusCode(400);
        return $view;
    }
    $em = $this->getDoctrine()->getManager();
    $entReps = $em->getRepository('PDOneBundle:Representative')->find($paramFetcher->get('rid'));
    if (!$entReps) {
        $view->setData(array('error' => 'object not found'))->setStatusCode(400);
        return $view;
    }
    .... some code
    $repsData = [];
    $view->setData($repsData)->setStatusCode(200);
    return $view;
}

如果我没有上传文件,我得到这样的响应:

Error: Call to a member function move() on a non-object
500 Internal Server Error - FatalErrorException

但是作为Symfony异常错误不像我想要和需要的JSON,所以代码永远不会进入if

如果我没有设置rid,那么我得到了这个错误:

Request parameter "rid" is empty
400 Bad Request - BadRequestHttpException

但再次作为Symfony异常错误,而不是作为JSON。如果rid不存在或文件未上传,我如何响应适当的JSON ?任何建议吗?

$request->filesFileBag的一个实例。使用$request->files->get('keyoffileinrequest')获取文件

rid是指定的是一个必需的参数,所以是的,它抛出一个BadRequestHttpException如果你不设置它。它就像它应该做的那样。您应该尝试将rid设置为数据库中没有的ID,然后您应该看到自己的错误消息。

如果你想让rid是可选的,你可以为rid添加一个默认值:

* @RequestParam(name="rid", nullable=false, requirements="'d+", default=0, description="The ID of the representative")

差不多。现在rid将为零,您的Repository::find调用可能会返回null,并且将返回错误视图。但我建议你保持原样,这是正确的行为。