Google API - incomprehensive "Invalid Credentials"
<p>I'm trying to combine two parts of Python3.5 code to work with Google Gmail API. One is getting access key with refresh key and confirmed it worked. The other is getting list of Gmail through API and confirmed it worked. I got "invalid credentials" error message when I combine those two codes.</p>

<h2>Snippet1: Getting refresh key (This works)</h2>

<pre><code>import requests
import json
import string

translator = str.maketrans({key: None for key in string.punctuation})

payload = {'grant_type': 'refresh_token',
       'refresh_token': '&lt;--- Token ----&gt;',
       'client_id': '&lt;----Client ID----&gt;',
       'client_secret': '&lt;----Client secret----&gt;',
       'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob',
       'scope': 'https://mail.google.com/'
      }
r = requests.post("https://accounts.google.com/o/oauth2/token", data=payload)
txt = r.text
key_json = json.loads(r.text)
key = json.dumps(key_json['access_token'], sort_keys = True, indent = 4)
print (key.translate(translator))
</code></pre>

<p>This code returns the access token without punctuation successfully.</p>

<h2>Snippet2: Getting Gmail list (This works)</h2>

<pre><code>import requests

Token = "&lt;----Access Token------&gt;"
Gmail_list ='https://www.googleapis.com/gmail/v1/users/me/messages/'
data = {'Authorization': 'Bearer ' + Token}
r3 = requests.get(Gmail_list, headers=data)
txt = r3.text
print (txt)
</code></pre>

<p>Now, I combined those two.</p>

<pre><code>import requests
import json
import string
import base64
import email

translator = str.maketrans({key: None for key in string.punctuation})
Gmail_list ='https://www.googleapis.com/gmail/v1/users/me/messages/'

payload = {'grant_type': 'refresh_token',
       'refresh_token': '&lt;----Token----&gt;',
       'client_id': '&lt;-----Client ID------&gt;',
       'client_secret': '&lt;-------Client secret------&gt;',
       'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob',
       'scope': 'https://mail.google.com/'
      }
r = requests.post("https://accounts.google.com/o/oauth2/token", data=payload)
key_json = json.loads(r.text)
key1 = (json.dumps(key_json['access_token'], sort_keys = True, indent = 4))
key2 = (key1.translate(translator))
r2 = {'Authorization': 'Bearer ' + key2}
r3 = requests.get(Gmail_list, headers=r2)
txt = r3.text
print (txt)
</code></pre>

<p>Then, I got following error.</p>

<pre><code>{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "authError",
    "message": "Invalid Credentials",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Invalid Credentials"
 }
}
</code></pre>

<p>I tried to figure out what's wrong but could not nail down the root cause..
Could you point out what's wrong on my code? Why Snippet1+2 does not work? Do I need to do something in Python requests module?</p>