I am making a POST
method for a RESTful API. The API is built on top of FOSRestBundle and NelmioApiDoc as you may notice. I am not able to validate when file is not uploaded or when rid
parameter is missing and response with proper JSON. This is what I am doing:
/**
* 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;
}
If I not upload a file I got this response:
Error: Call to a member function move() on a non-object
500 Internal Server Error - FatalErrorException
But as Symfony exception error not as a JSON as I want and need, so code is never entering in the if
.
If I not set rid
then I got this error:
Request parameter "rid" is empty
400 Bad Request - BadRequestHttpException
But again as Symfony exception error and not as a JSON. How do I response a proper JSON if rid
is not present or if file wasn't uploaded? Any advice?
$request->files
is an instance of FileBag
. Use $request->files->get('keyoffileinrequest')
to get the file.
rid
is specified is a required parameter, so yeah, it throws a BadRequestHttpException if you don't set it. It behaves like it should. You should try setting rid
to an ID that isn't in the database, then you should see your own error message.
If you want rid
to be optional you could add a default value for rid
:
* @RequestParam(name="rid", nullable=false, requirements="\d+", default=0, description="The ID of the representative")
Something like that. Now rid
will be zero, your Repository::find call will probably return null and your error view will be returned. But I recommend that you keep it like it is, it is proper behavior.