I'm working on a project written in Symfony 3 and I have to make a REST API Controller.
I have classic rout for example:
/users : (GET)get all users
/users/{id} : (GET) get a single user
/users : (POST) create a user
and so on..
But I would like to know how to implement a route to search with multiple parameter a user like this URL:
/users?name=John&surname=Doe&age=20&city=London
How can I create this route with query string and search inside it if a value isn't set?
This is a piece of my controller
namespace AppBundle\Controller;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Controller\FOSRestController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\HttpException;
use AppBundle\Entity\User;
use AppBundle\Form\UserType;
class UserController extends FOSRestController
{
/**
* @Rest\Get("/users")
*/
public function getUsersAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$users = $em->getRepository(User::class)->findAll();
if (!$users) {
throw new HttpException(400, "Invalid data");
}
return $users;
}
/**
* @Rest\Get("/users/{userId}")
*/
public function getUsersByIdAction($userId, Request $request)
{
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository(User::class)->find($userId);
if (!$userId) {
throw new HttpException(400, "Invalid id");
}
return $user;
}
/**
* @Rest\Post("/users")
*/
public function postUsersAction(Request $request)
{
$user = new User();
$form = $this->createForm(UserType::class, $user);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
return $user;
//return new JsonResponse( [$data, $status, $headers, $json])
}
throw new HttpException(400, "Invalid data");
}
}