title: How can I get an oauth2 access_token using Python
body: <p>For a project someone gave me this data that I have used in Postman for testing purposes:</p>
  
  <p>In Postman this works perfectly.</p>
  
  <p>Auth URL: <a href="https://api.example.com/oauth/access_token" rel="noreferrer">https://api.example.com/oauth/access_token</a><br>
  Access Token URL: <a href="https://api.example.com/access_token" rel="noreferrer">https://api.example.com/access_token</a><br>
  client ID: abcde<br>
  client secret: 12345<br>
  Token name: access_token<br>
  Grant type: Client Credentials  </p>
  
  <p>All I need is to get back the access token. </p>
  
  <p>Once, I got the access token I can continue. </p>
  
  <p>I have already tried several Python packages and some custom code, but somehow this seemingly simple task starts to create a real headache. </p>
  
  <p>One exemple I tried:</p>
  
  <pre><code>import httplib
  import base64
  import urllib
  import json
  
  def getAuthToken():
      CLIENT_ID = "abcde"
      CLIENT_SECRET = "12345"
      TOKEN_URL = "https://api.example.com/oauth/access_token"
  
      conn = httplib.HTTPSConnection("api.example.com")
  
      url = "/oauth/access_token"
  
      params = {
          "grant_type": "client_credentials"
      }
  
      client = CLIENT_ID
      client_secret = CLIENT_SECRET
  
      authString = base64.encodestring('%s:%s' % (client, client_secret)).replace('\n', '')
  
      requestUrl = url + "?" + urllib.urlencode(params)
  
      headersMap = {
          "Content-Type": "application/x-www-form-urlencoded",
          "Authorization": "Basic " + authString
      }
  
      conn.request("POST", requestUrl, headers=headersMap)
  
      response = conn.getresponse()
  
      if response.status == 200:
          data = response.read()
          result = json.loads(data)
  
          return result["access_token"]
  </code></pre>
  
  <p>Then I have got this one:</p>
  
  <pre><code>import requests
  import requests.auth
  
  CLIENT_ID = "abcde"
  CLIENT_SECRET = "12345"
  TOKEN_URL = "https://api.example.com/oauth/access_token"
  REDIRECT_URI = "https://www.getpostman.com/oauth2/callback"
  
  def get_token(code):
      client_auth = requests.auth.HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET)
      post_data = {"grant_type": "client_credentials",
                   "code": code,
                   "redirect_uri": REDIRECT_URI}
      response = requests.post(TOKEN_URL,
                               auth=client_auth,
                               data=post_data)
      token_json = response.json()
      return token_json["access_token"]
  </code></pre>
  
  <p>If this would work, what should I put into the <code>code</code> parameter</p>
  
  <p>I really hope someone can help me out here. </p>
  
  <p>Thanks in advance.</p>