views:

955

answers:

2

I am making an API for some AJAX related things in my web app on GAE in Python. After setting the content-type to 'application/json' and accessing my url directly-

http://mysite.com/api?method=theMethod&param=firstParam

-I am being prompted with a 'save file' dialog box instead of seeing the JSON object displayed. The file contains the JSON object when opened in notepad.

Is this a correct way to return JSON from Python using GAE to be parsed in JavaScript?

from django.utils import simplejson
self.response.headers['Content-Type'] = 'application/json'
jsonData = {"foo" : "bar"}
self.response.out.write(simplejson.dumps(jsonData))

I have noticed that when using another API from somewhere else such as Flickr, my browser displays the JSON object rather than asking for me to save the file. This behavior is what encouraged me to investigate my implementation. My only thought is that this is related to a JSONP implementation.

Judging from rfc4627, I should be using 'application/json'.

+1  A: 

I think the Flickr API returns the json as type 'text/plain' which then will be displayed as text. You might try 'text/json' as a halfway point. Being easily viewed might outweigh being correct in your case.

Also consider that should any client require the content type to be 'application/json' and refuse to work with 'text/plain' that client should specifically request the type it wants without '/'. This then could be a case you look for when preparing the content type of your response, and you could document your service accordingly.

See Request:

http://www.flickr.com/services/rest/?method=flickr.test.echo&format=json&api_key=cecc9218c59188ebc6150eff9cd908dc

Request Headers

Accept:application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Referer:http://www.flickr.com/services/api/response.json.html
User-Agent:Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_7; en-us) AppleWebKit/530.18 (KHTML, like Gecko) Version/4.0.1 Safari/530.18

Response Headers

Connection:close
Content-Encoding:gzip
Content-Length:134
Content-Type:text/plain; charset=utf-8
Date:Thu, 02 Jul 2009 03:19:34 GMT
P3p:policyref="http://p3p.yahoo.com/w3c/p3p.xml", CP="CAO DSP COR CUR ADM DEV TAI PSA PSD IVAi IVDi CONi TELo OTPi OUR DELi SAMi OTRi UNRi PUBi IND PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA POL HEA PRE GOV"
Vary:Accept-Encoding

Content

jsonFlickrApi({"method":{"_content":"flickr.test.echo"}, "format":{"_content":"json"}, "api_key":{"_content":"cecc9218c59188ebc6150eff9cd908dc"}, "stat":"ok"})
dlamblin
These are the results that I found too which made me question my implementation.
Jason Rikard
+4  A: 

This is the right way, mime type for json is application/json not text/json and NEVER text/html. http://tools.ietf.org/html/rfc4627 starts with "The application/json Media Type for JavaScript Object Notation (JSON)"

read this for more details/options

Anurag Uniyal