Home Ask Login Register

Developers Planet

Your answer is one click away!

Benjamin Rasmussen February 2016

Symfony2: FOSRest: Allow route for both "/api/items" and "api/items/{id}"

So, I'm trying to create a simple REST api with Symfony2 and the FOSRestBundle.

It's going really well, however I've hit a wall that Google apparantly hasnt been able to answer :)

I understand that this:

public function getUsersAction(){
  return 'A list of all the users';
}

Will create a route as such:

  api_get_users              GET      ANY      ANY    /api/users.{_format}                       

And I know that add a function parameter:

public function getUsersAction($id){
  return 'A specific users (with $id) details';
}

Will create a route as such:

  api_get_users              GET      ANY      ANY    /api/users/{userid}.{_format}              

However what if I want to make it, so both routes are available (like a proper REST api design)?

I tried doing something like

public function getUsersAction($userid = NULL){

But it didnt work (not a huge surprise)..

I'm pretty sure that I'm missing a simple piece of the puzzle, but I have no idea what.

Answers


Wouter J February 2016

Creating a getUserAction($id) and a getUsersAction() (not plural) should work, according to the documentation:

class UserController implements ClassResourceInterface
{
    // ...

    public function getUsersAction()
    {} // "get_users"     [GET] /users

    public function getUserAction($slug)
    {} // "get_user"      [GET] /users/{slug}

    // or when omittig "User":

    public function cgetAction()
    {} // "get_users"     [GET] /users

    public function getAction($slug)
    {} // "get_user"      [GET] /users/{slug}

    // ...
}

Post Status

Asked in February 2016
Viewed 2,036 times
Voted 14
Answered 1 times

Search




Leave an answer


Quote of the day: live life