0

I am trying to rewrite the following url,

http://mywebsite.com/web/myContlr?myContlrSearch[id]=900

Using Yii2 Url manager i am trying to change the url to be as below,

http://mywebsite.com/web/myContlr/900

How can this above format possible using urlmanger rules in Yii2. And also I am having multiple parameters like myContlrSearch[name], myContlrSearch[location],.. etc

Please guide me to build the URL restful.

Nana Partykar
  • 10,175
  • 8
  • 43
  • 73
Akilan
  • 1,677
  • 1
  • 14
  • 28
  • do you mean like this ? http://stackoverflow.com/questions/25522462/yii2-rest-query/30560912#30560912 (see original answer vs last update) – Salem Ouerdani Aug 10 '16 at 17:08

1 Answers1

0

If You want to make your API RESTful then You should start from resource naming. Resources should be a nouns in plural form.

For example if you have some class like a "car" then corresponding resource url should looks like <your-domain>/cars. In this case GET /cars will be a method to get a collection of cars, and GET /cars/900 -- a method to get specific car with ID=900.

Next, if your parameters are needed for filtering resource collection then you should add them as query parameters to collection resource url, like this: /cars?vendor=ferrari&count=10. If your parameters are needed to specify instance properties (when you create or update some object), then you should include them into a request body.

For instance creation you should use url of resource collection: POST /cars. And for updating an instance -- PUT /cars/<id>.

Lets look on your particular case. You have some resource named myContlr (i hope this is just example name), so myContlr should be an noun which express a object name. Your myContlrSearch in query parameters looks like some search criteria object, so it can be passed as array or as json in query parameters (it's better do not use request body for GET requests). Using array/json/any-other-structure here will not affect your routing -- this should be within the scope of responsibility of the controller.

But if you want to create new object or update existing one, then you should use POST /myContrlr or PUT /myContrlr/900 and then pass your object in request body (of type application/json or application/xml).

Then your routing config can looks as follows:

$config['components']['urlManager'] = [
    ...
    'rules' => [
        'GET myContlr/<id:\d+>' => 'myContlr/view',
        'PUT myContlr/<id:\d+>' => 'myContlr/update',
        'DELETE myContlr/<id:\d+>' => 'myContlr/delete',
        'GET myContlr' => 'myContlr/index',

To learn more about building RESTful API in Yii2: http://www.yiiframework.com/doc-2.0/guide-rest-quick-start.html

For further reading: http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api

Community
  • 1
  • 1
oakymax
  • 1,376
  • 1
  • 10
  • 20