phprestapiyii2yii-url-manager

Yii2 rest api - Url manager add parameters


I am working on an api that has 4 levels of users. Admin, reseller, channel and customer. All levels have call rates stored in respective _rate tables.

Admin can view rates for all user levels, resellers can view their own rates and all of their channels and customers, channels themselves and their customers etc.

So when an reseller fires:

api.dev/v1/call-rates

tbl_reseller_rate is returned however I want to be able to specify whose rates I want to look at for example

api.dev/v1/call-rates/channels

or

api.dev/v1/call-rates/customers

so then I can do something like:

if (strpos($url,'channels') !== false) 
{
    flip to channel model; 
} else if (strpos($url,'customers') !== false) 
{
    flip to customer model; 
}

Another requirement is to view records individually so the url needs to accept an ID parameter as well like so:

api.dev/v1/call-rates/channel/1

Any help would be massively appreciated. Thanks in advance


Solution

  • You should configure your REST Url like this:

    [
        'POST v1/call-rates/<type>' => 'your_controller/call_rates',
        'POST v1/call-rates/<type>/<id>' => 'your_controller/call_rates',
    ]
    

    and in your controller file

    public function call_rates($type, $id = null){
         if(!in_array($type, ['customer','channels'])) {
            // throw bad request exception here 
         }
    
         // Do what ever you want with $type variable.
    
    }
    

    FOR ID route you can change the method for it, just for the example i've route it to the same method in the controller.

    See more on the REST routes