Relational Routing for REST API in Yii2

How to configure relational routing in config file for REST API.

Long story short question: How to configure config/main.php to get this url


app.com/api/v1/roles/1/users

Full question:

I have already configured route for users and roles like this




GET all users

app.com/api/v1/users 


GET user 1

app.com/api/v1/users/1


GET all roles

app.com/api/v1/roles


GET role 1

app.com/api/v1/roles/1



For the above routing i have something like this in my common/config/main.php. And i have placed model User and Role in modules/v1/models and placed controller UserController and RoleController in modules/v1/controller.




        'urlManager' => [

            'enablePrettyUrl' => true,

            'showScriptName' => false,

            'rules' => [

                [

                    'class' => 'yii\rest\UrlRule',

                    'controller' => [

                        'v1/user',

                        'v1/role'

                    ],

                    'tokens' => [

                        '{id}' => '<id:\\w+>'

                    ],

                ]

            ],


        ],



So what should i write in the urlManager to get the users of a particular role in this url format

app.com/api/v1/roles/1/users GET

Do you have a solution to this problem? I have been trying to do something similar.

Currently I can request a list of all authors in my database


GET http:api.site.com/v1/author

I can get the details for a single author


GET http:api.site.com/v1/author/123

I want to be able to fetch other relational information about the author in a rest format. Example if I wanted to request all the books for an author I would expect that a nice clean REST API url structure to look like this.


GET http:api.site.com/v1/author/123/book

and if I wanted to get the details for a single book I would do this.


GET http:api.site.com/v1/author/123/book/321