Search code examples
pythonjsonoauthpython-requestspython-requests-html

Requesting an API call that requires an oauth token in python


So i'm writing a program that post's data to a url and get's the response. In postman it requires a token. So when I tried to make it in python it's giving me a response [401].

The problem I have is trying to get the token first and then passing it to my post_data method.

I'm going to put *** by the URL and username and password for privacy concerns.

import requests
import json
import pprint
import urllib

def get_token():
    tokenurl='***'
    data={
            'grant_type':'password',
            'username':'***',
            'password':'***'
            }
    token=requests.post(tokenurl,data=data)
    print(token)    
get_token()

def post_data():
    url1='***'
    data={"***"
      }

    data_json = json.dumps(data)
    headers = {'Content-type': 'application/json'}
    response = requests.post(url, data=data_json, headers=headers)
    pprint.pprint(response.json())


Solution

  • In the post_data() function, you can add your generated token to the headers

    headers = {'Content-type': 'application/json','Authorization': 'token ***'}
    

    *** is your generated token