1

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.