Tuesday, July 22, 2014

taste of python Requests

I barely use REST api with Python, but recently I found a great (and easy) Python library for HTTP/REST APIs, Python Requests.

It needs zero effort for installing, with pip or easy_install ("easy_install requests" for my MacOS)

First try with GET
 import requests  
 r = requests.get('https://example.com')  

GET with parameter
 param = {‘user_id’:12345}  
 r = requests.get('https://example.com’, param)  
 #to get the content of the response  
 print r.text  
 # it can also parse to json data  
 data = json.loads(r.text)  

check with status code
 print r.status_code  

for bad request, raise exceptions
 print r.raise_for_status()  

Session objects are pretty helpful
I used POST to carry to auth cookies through from authentication 
 s = requests.Session()  
 url = ‘api.example.com’  
 info = {‘user’:”usename’, ‘password’:’mypassword’}  
 r = s.post(url, data = info)  

I got an error at the first beginning 
 requests.exceptions.SSLError: hostname 'api.example.com' doesn't match 
 either of ‘example.com', 'www.example.com’  

It seems the POST method checked the host’s SSL certificate. In this case we just need set the verify flag as False
 r = s.post(url, data = info, verify=False) 

dah-dah!! it got through, then I can do GET, POST and DELETE to play with the data through the api

useful resource: handy cheat sheet for beginners

No comments:

Post a Comment