Sample code.Python. Perl. Language Ajax api. Post method. 5000. api limit.

12 views
Skip to first unread message
Message has been deleted

tcs 241

unread,
May 10, 2009, 5:02:49 AM5/10/09
to Google AJAX APIs
The post title is a set of keywords I used for googling to find
answer. I've tried all combination. Basically, due to not familiar
with protocols and few explicit explanation out there, the whole
finding really took a while.

Perl sample code:
http://search.cpan.org/dist/WebService-Google-Language-0.09/lib/WebService/Google/Language.pm

this is Perl translation module utilizing google language Ajax api.

When encoded url with translation test is less than 2000 something or
Maximum url length set by google server, this module uses GET method.

When translation test is between 2000 and 5000, this module will put
encoded translation text, api version, and langpair etc in body and
send by POST method.

You can download Perl from (http://www.perl.org/get.html) and install
this module.

Python sample code:

POST method
First please download http://code.google.com/p/python-rest-client/

############################
#POST method
############################
from restful_lib import Connection
import urllib

conn = Connection('http://ajax.googleapis.com/ajax/services/language')

query = {'v':'1.0', 'langpair':'en|de','q':'hello world'};

print conn.request_post("/translate",body=urllib.urlencode(query),
headers={'referer':'http://example.com', "content-type":"application/x-
www-form-urlencoded" ,"charset":"UTF-8"})

#############################

notes:
1. query needs to be encoded as a string 'q=hello+world&langpair=en
%7Cde&v=1.0' with urlencode()

2. "content-type":"application/x-www-form-
urlencoded" ,"charset":"UTF-8" shold be added to headers to tell
server how 'body' is encoded.

Without them, you will get 'invalid version' error in response.

3. based on perl module description (http://search.cpan.org/dist/
WebService-Google-Language-0.09/lib/WebService/Google/
Language.pm#CONSTRUCTOR)
header 'referer':'http://example.com' is mandatory, because Google
demands a "valid and accurate http referer header" in requests to
their service.

4. If you want to use it one google app engine, please use 'from
gae_restful_lib import GAE_Connection as Connection' instead (
http://code.google.com/p/python-rest-client/wiki/REST_for_Google_App_Engine
)

5. Please try a longer translation text, after you get sample code
work.

BTW, here is GET method sample code
############################
#GET method
############################
from restful_lib import Connection

print conn.request_get("/translate", args={'v':'1.0','langpair':'en|
de','q':'Hello'}, headers={'referer':'http://
example.com','Accept':'text/json'})

#############################

useful tool for restful testing:
http://code.google.com/p/rest-client/

Chef
my ads:
U.S. Immigration Guide
http://visachoice.appspot.com


Reply all
Reply to author
Forward
0 new messages