ews2001
ews2001

Reputation: 2187

Yii UrlManager: How use Ruby REST for .json and .xml files in my API?

I'm creating a REST API in Yii and I'd like to build my URLs like this:

/api/my_model
/api/my_model.xml
/api/my_model.json

Where the first one returns the HTML view, .xml returns XML and .json returns JSON.

This is what I have in the rules for urlManager in main.php:

array('api/list/', 'pattern'=>'api/<model:\w+>', 'verb'=>'GET'),

I figure if I pass a format variable, then if it's blank I know it should return HTML, or json/xml if a format is passed. I tried this:

array('api/list/', 'pattern'=>'api/<model:\w+>.<format:(xml|json)>', 'verb'=>'GET'),

And it works great for .xml and .json, but not when my url is just /api/list

My question is how do I setup the URLs in urlManager to make this work?

Upvotes: 1

Views: 655

Answers (1)

bool.dev
bool.dev

Reputation: 17478

In php regular expressions, ? is used to match 1 or none of the previous character, so

a? means zero or one of a

Then we can use that in the rule:

array('api/list/', 'pattern'=>'api/<model:\w+>.<format:(xml|json)>?', 'verb'=>'GET'),
// notice the ? at the end of format:

However the above will also allow urls of type : api/my_model.

To avoid that you can move the dot into the format variable :

array('api/list/', 'pattern'=>'api/<model:\w+><format:(.xml|.json)>?', 'verb'=>'GET'),

But that will result in format being .xml or .json. So, we have another alternative:

array('api/list/', 'pattern'=>'api/<model:\w+>(.<format:(xml|json)>)?', 'verb'=>'GET'),

This should work with all urls, you wanted, and also match format as either xml or json.

Upvotes: 2

Related Questions