Python Social Media Analytics
上QQ阅读APP看书,第一时间看更新

Practical usage of OAuth

In this part of the chapter, we will see how to connect to the main social media using OAuth and how to get and parse the data. There are many libraries in Python 3 implementing the OAuth protocol. For the purposes of this book, we will show how to use a library called requests.

The requests library implements the whole range of authentication protocols and allows you to execute HTTP requests such as GET or POST.

Firstly, you have to import the library in your code:

import requests 

If you are using the OAuth protocol, you import the related library:

from requests_oauthlib import OAuth1 

Then, you have to create your authenticated connection using access tokens and application keys that you will find in the developer console:

auth = OAuth1('YOUR_APP_KEY', 'YOUR_APP_SECRET', 'USER_OAUTH_TOKEN', 'USER_OAUTH_TOKEN_SECRET') 

Then, you can make GET requests:

r = requests.get('https://api.sampleurl.org/get',auth=auth) 

Pass these parameters:

payload = {'key1': 'value1', 'key2': 'value2'} 
r = requests.get('http://sampleurl.org/get', params=payload) 

POST requests:

r = requests.post('http://sampleurl.org/post', data = {'key':'value'}) 

Also, a whole range of additional requests:

r = requests.put('http://sampleurl.org/put', data = {'key':'value'}) 
r = requests.delete('http://sampleurl.org/delete') 
r = requests.head('http://sampleurl.org/get') 
r = requests.options('http://sampleurl.org/get') 

In order to parse the outputs, you can use different methods such as:

  • r.text() This gets a string with request outputs
  • r.json(): This gets JSON with request outputs
  • r.econding(): This checks the encoding of the output