Mixing route and query parameters using FOSRestBundle with Symfony

前端 未结 2 1211
-上瘾入骨i
-上瘾入骨i 2021-02-05 23:27

Using Symfony2 and FOSRestBundle I am attempting to implement API methods that have some number of fixed parameters defined in the route along with some optional parameters that

2条回答
  •  悲哀的现实
    2021-02-06 00:02

    This question is quite old and you probably found a solution already but since I got here through Google search and know an answer I will contribute.

    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    use Symfony\Component\HttpFoundation\JsonResponse;
    use FOS\RestBundle\Request\ParamFetcher;
    use FOS\RestBundle\Controller\Annotations\QueryParam;
    use Nelmio\ApiDocBundle\Annotation\ApiDoc;
    
    class DefaultController extends Controller
    {
        /**
         * Returns a collection of Task
         *
         * @QueryParam(name="projectId", nullable=true, requirements="\d+")
         * @QueryParam(name="name", nullable=true, description="Project Name")
         * @QueryParam(name="assignee", nullable=true)
         * @QueryParam(name="depth", nullable=true)
         *         *
         * @param ParamFetcher $paramFetcher
         * @ApiDoc()
         *
         * @return JsonResponse
         */
        public function cgetTaskAction(ParamFetcher $paramFetcher)
        {
            foreach ($paramFetcher->all() as $criterionName => $criterionValue) {
                // some logic here, eg building query
            }
    
            $results = // query database using criteria from above
    
            // this is just a simple example how to return data
            return new JsonResponse($results);
        }
    }
    

提交回复
热议问题