views:

554

answers:

3

Hi, I'm developing a REST CodeIgniter Controller and need to POST and PUT to a URL in multiple formats.

The main formats I can think of would be:

  • XML
  • JSON
  • HTML Form data

There will be a response format defined in the URI e.g. /format/xml or /format/csv. I don't want to have to define the request format in the URI as well.

I was wondering if anyone has any suggestions on finding out the request format so my script can complete the request.

I'm thinking it may be possible to get this data from the request headers "content-type"?

  • "content-type: text/xml" = XML
  • "content-type: application/json" = JSON
  • "content-type: text/plain" = HTLM Form data *i think!

Would this method be robust or are there better approaches out there?

Thanks.

A: 

That method is robust as long as you know the your REST client will follow your content-type rule. If you control the client then this is fine. If you don't control the client then how acceptable is failure of the call when an unusual (or no) content-type is passed in?

Oh and for reference HTML form data has a content type of 'application/x-www-form-urlencoded'

Dolbz
Thanks, who the hell came up with that snappy string :-)
th3hamburgler
+2  A: 

The content-type is the correct way to get the information you want.

Just make sure to throw an exception with some feedback and the correct http error code if the client calls it on the wrong format or do not pass the content-type header (you could also assume one content-type as default)

Also, you don't really have to use format/format_of_the_response . A better way would be to use the header Accept on the same way you use the header content-type

Diego Dias
Thanks, I think i'll look into using the accept header too! Hope I can set headers from jquery forms, definitely more elegant
th3hamburgler
+1  A: 

I know this has been answered, but Phil Sturgeon wrote a REST Client and REST Server Library for codeigniter, might help you out a little bit.

http://github.com/philsturgeon/codeigniter-restclient

Zack