Search code examples
phprestsymfonyphpunitfosrestbundle

fos rest custom get url in symfony2


I need to create a custom url in my rest api. I am using fos rest bundle.

custom URL is like:

http://myapi.com/api/v1/public/users/confirm?cd=<some_code>.json

I have tried:

@GET("/users/confirm?cd={cd}")

and when I run:

php /app/console route:debug

I am getting this:

...
....
get_confirm GET ANY ANY  /api/v1/public/users/confirm?cd={cd}.{_format}
...
...

but in my test when I try to hit this URL I get:

No route found for &quot;GET /api/v1/public/users/confirm&quot; (404 Not Found)

can anyone help me in this. How to form such URLs.

My Controller Action Code:

/*
 * @GET("/users/confirm?cd={cd}")
 */
public function getConfirmAction($cd) {

    //Some code for user confirmation

    return return View::create(array('successmessage'=>'Your account has been verified successfully. Please login.', Codes::HTTP_OK);
}

PHPUnitTest Code:

public function testGetConfirmThrowsInvalidArgumentException() {
    $this->client->request(
                'GET', '/api/v1/public/users/confirm?cd=abcd123.json'
        );

        $response = $this->client->getResponse();

        print_r($response->getContent());
        exit(__METHOD__);
}

Solution

  • Agreed with @john comment: you dont need to add the queryparameters to your route definition

    I guess basically you are looking to have a parameter always supplied with the URL. If this is your requirement then FOSRestBundle has cool feature called as param fetcher. With it you can define your query string parameters with annotations, allow them nullable or not, set default values, define requirements.

    for your case if you are expecting cd to be a number then you can have annotations as

    @QueryParam(name="cd", nullable=true, requirements="\d+")
    

    see below example for sample code

    /*
    * function desc
    * @QueryParam(name="cd", nullable=true, requirements="\d+")
    * @param ParamFetcher $paramFetcher
    */
    public function getConfirmActionAction(ParamFetcher $paramFetcher)
    {
       //access the parameter here
        foreach ($paramFetcher->all() as $name => $value) {
            echo $name."==>". $value;
        }
    
    }