I'm currently developing an API for my application on RoR
As an example, I created some XML, loaded with all the info I need to create the object, let's say a Person, and using Curl I submitted it to my application
I'm able to call exactly the create action I want from the controller and the hash params of the object are being passed correctly
But now I need to apply a different behaviour if request was made or not with XML, what is bothering me is why in the controller request.format
gives */*
.
Any clues?
curl -v -H "Content-Type: application/xml; charset=utf-8" --data-ascii @client.xml http://foo.com:3000/clients?api_key=xxx
def create
logger.debug request.format # produces "*/*"
if request.format.xml?
# never gets here
end
end
*/*
means that the user-agent accepts all formats and doesn't care what format you give it. I believe Safari does this, among others. By default,curl
sends an Accept header of*/*
.Here is a dump of the headers
curl
sends by default:However, in this case, it looks like you want to send back XML if the payload sent to you was XML? If that's the case, you want to check the request's Content-Type header directly. i.e.,
request.content_type
is the method you want.Addenda: I thought a bit more about this, and I think the best approach is to first check
request.format
and only if that is inconclusive checkrequest.content_type
. Essentially, the HTTP spec provides for clients being able to tell servers that "I'm giving you XML, but I want JSON back." The Accept header is how clients tell you what they want back, and if someone actually sends it, you should honor that. Only use the request's Content-Type as a hint if the client didn't specify.*/*
simply means that all MIME types are accepted.Looking at the code for the
request.format
method, the MIME type is determined by the file extension, or if that's not present then by the value of the HTTP Accept header. So you either need to pass Curl an XML file saved to disk, or get Curl to set the Accept header to an XML MIME type (e.g.text/xml
) when it makes the request to your API.