How to add http headers along with data to send a POST request to an API endpoint using Oauth2Session (requests_oauthlib)?

2.2k views Asked by At

I have a python code like this to interact with an API

from oauthlib.oauth2 import BackendApplicationClient
from requests_oauthlib import OAuth2Session
import json
from pprint import pprint

key = "[SOME_KEY]"          # FROM API PROVIDER
secret = "[SOME_SECRET]"    # FROM API PROVIDER

api_client = BackendApplicationClient(client_id=key)
oauth = OAuth2Session(client=api_client)

url = "[SOME_URL_FOR_AN_API_ENDPOINT]"
# GETTING TOKEN AFTER PROVIDING KEY AND SECRET
token = oauth.fetch_token(token_url="[SOME_OAUTH_TOKEN_URL]", client_id=key, client_secret=secret)

# GENERATING AN OAuth2Session OBJECT; WITH THE TOKEN:
client = OAuth2Session(key, token=token)
body = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
}
response = client.post(url, data=json.dumps(body))
pprint(response.json())

When I run this py file, I get this response from the API, that I have to include the content type in the header. How do I include the header with Oauth2Session?

{'detailedMessage': 'Your request was missing the Content-Type header. Please '
                    'add this HTTP header and try your request again.',
 'errorId': '0a8868ec-d9c0-42cb-9570-59059e5b39a9',
 'simpleMessage': 'Your field could not be created at this time.',
 'statusCode': 400,
 'statusName': 'Bad Request'}
2

There are 2 answers

0
Joshua Maerker On BEST ANSWER

Have you tried to you send a header paramter with this requests?

headers = {"Content-Type": "application/json"}
response = client.post(url, data=json.dumps(body), headers=headers)
0
bradbase On

This is how I was able to configure the POST request for exchanging the code for a token.

from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import WebApplicationClient, BackendApplicationClient
from requests.auth import HTTPBasicAuth

client_id = CLIENT_ID
client_secret = CLIENT_SECRET
authorization_base_url = AUTHORIZE_URI
token_url = TOKEN_URI
redirect_uri = REDIRECT_URI
auth = HTTPBasicAuth(client_id, client_secret)
scope = SCOPE
header = {
  'User-Agent': 'myapplication/0.0.1',
  'Content-Type': 'application/x-www-form-urlencoded',
  'Accept': 'application/json',
}

# Create the Authorization URI
# Not included here but store the state in a safe place for later
the_first_session = OAuth2Session(client_id=client_id, redirect_uri=redirect_uri, scope=scope)
authorization_url, state = the_first_session.authorization_url(authorization_base_url)

# Browse to the Authorization URI

# Login and Auth with the OAuth provider

# Now to respond to the callback

the_second_session = OAuth2Session(client_id, state=state)

body = 'grant_type=authorization_code&code=%s&redirect_uri=%s&scope=%s' % (request.GET.get('code'), redirect_uri, scope)
token = the_second_session.fetch_token(token_url, code=request.GET.get('code'), auth=auth, header=header, body=body)