views:

80

answers:

2

Good afternoon,

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

Thanks in advance

+1  A: 

*/* 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:

User-Agent: curl/7.18.1 (i386-apple-darwin9.6.0) libcurl/7.18.1 zlib/1.2.3
Host: example.com
Accept: */*
Content-Type:

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 check request.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.

Bob Aman
browser? Hmm, now you got me confused. I'm sending the request via a command-line, browser type shouldn't be an issue
Yise
Yeah, sorry... I'll clarify.
Bob Aman
Now it makes more sense =) thank you
Yise
A: 
John Topley
Why the down vote?
John Topley
This isn't correct. He **is** passing an XML file. The payload of the request doesn't have any effect on request.format. You have to detect that manually. The request.format method uses the path component of the URI requested to get the format. So if your URI ends in .xml he'll get the expected value. However, if the goal is to provide a single API endpoint that handles multiple Content-Types, that won't help.
Bob Aman
Currently im using content-type as application/xml, changed to text/xml and it still produces the same request.format ( */* )The file passed to curl is saved on disk
Yise
OK, I misunderstood.
John Topley
@Yise Right. The request's Content-Type has no effect whatsoever on the return value of `request.format`.
Bob Aman