简体   繁体   中英

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.

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} // ... } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM