Unable to get Python requests with API token - python-3.x

This is my code:
import requests
API key correct
api_key = c87cabcf1b479b807a7b3ba8xxxxxxxxxxxxxx
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Token token=api_key'
}
Getting a List of serves from this API
r = requests.get('https://myserver/api/v1.1/server/', headers = headers, verify=False)
print(r.json())
print (r.status_code)
I am getting the error below. I checked my token correct one and not expires.
r.json() : {'error': {'code': 'error', 'description': 'Authentication credentials were not provided.'}}
r.status_code : 401
I missed somewhere in the header.

I guess problem is may be in your third line of header. Try it like this.
'Authorization': 'Token ' + api_key

Related

Why I am getting invalid token error when I am giving the right token

I am trying to get data from Zendesk using python. They have the following instruction in their API documentation. Though I am giving the right API token, I am getting an invalid authorization error.
Zendesk doc:
GET /v3/deals/custom_fields
Authorization: Bearer $TOKEN
My attempt:
import requests
import json
domain = 'https://mydomain.zendesk.com/v3/deals/custom_fields.json'
api_token= 'apikey'
payload = ""
headers = {
'Accept': "application/json",
'Content-Type': "application/json",
'Authorization': "Bearer "+api_token
}
response1=requests.request("GET", domain, data=payload, headers=headers)
response1.json()
Error:
{'error': 'invalid_token',
'error_description': 'The access token provided is expired, revoked, malformed or invalid for other reasons.'}

from docusign sdk i am trying to get envelope but getting "Reason: The URL provided does not resolve to a resource." 404 error

I am trying to create envelope from SDK but getting error like this
Reason: The URL provided does not resolve to a resource.
HTTP response headers: HTTPHeaderDict({'Cache-Control': 'no-cache', 'X-DocuSign-TraceToken': '22dad523-9f77-4b83-9481-1e376faf60d8', 'Date': 'Thu, 05 Dec 2019 13:02:26 GMT', 'Content-Length': '0'})
def worker(args):
"""
1. Create the envelope request object
2. Send the envelope
"""
envelope_args = args["envelope_args"]
#print(args)
#print("envelope arrrgggsss")
#print(envelope_args)
# 1. Create the envelope request object
envelope_definition = make_envelope(envelope_args)
#print(envelope_definition)
# 2. call Envelopes::create API method
# Exceptions will be caught by the calling function
api_client = ApiClient()
api_client.host = args["base_path"]
print(api_client.host)
api_client.set_default_header("Authorization", "token" + args["ds_access_token"])
envelopes_api = EnvelopesApi(api_client)
results = envelopes_api.create_envelope(args['account_id'], envelope_definition=envelope_definition)
#print(results)
envelope_id = results.envelope_id
app.logger.info(f"Envelope was created. EnvelopeId {envelope_id}")
return {"envelope_id": envelope_id}
Before that i try to get the token from the following code
def oauth2_token_request(root_url, username, password,
integrator_key):
url = root_url + '/oauth2/token'
data = {
'grant_type': 'password',
'client_id': integrator_key,
'username': username,
'password': password,
'scope': 'api',
}
headers = {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
}
response = requests.post(url, headers=headers, data=data)
print(response)
if response.status_code != 200:
raise exceptions.DocuSignOAuth2Exception(response.json())
return response.json()['access_token']
def oauth2_token_revoke(root_url, token):
url = root_url + '/oauth2/revoke'
data = {
'token': token,
}
headers = {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
}
response = requests.post(url, headers=headers, data=data)
return response
# if response.status_code != 200:
# raise exceptions.DocuSignOAuth2Exception(response.json())
It seems you are hitting wrong API endpoint as
/restapi/v2.1/accounts/9286679/restapi/v2.1/accounts/9286679/envelopes
whereas the correct URI is
/restapi/v2.1/accounts/9286679/envelopes
check your "base_path" value.

Morningstar with python requests to get 10 year financial data

It seems morningstar login solution in How can I log in to morningstar.com without using a headless browser such as selenium? is not working anymore for me.
I get error message {'message': 'Forbidden'} and I believe this is because of the login_url used in the solution "https://www.morningstar.com/api/v2/user/login"
Is there any workaround?
import requests
s = requests.session()
auth_url = 'https://sso.morningstar.com/sso/json/msusers/authenticate'
login_url = 'https://www.morningstar.com/api/v2/user/login'
username = 'username'
password = 'password'
headers = {
'Access-Control-Request-Method': 'POST',
'Access-Control-Request-Headers': 'content-type,x-openam-password,x-openam-username',
'Origin': 'https://www.morningstar.com'
}
s.options(auth_url, headers=headers)
headers = {
'Referer': 'https://www.morningstar.com/members/login.html',
'Content-Type': 'application/json',
'X-OpenAM-Username': username,
'X-OpenAM-Password': password,
'Origin': 'https://www.morningstar.com',
}
s.post(auth_url, headers=headers)
data = {"productCode":"DOT_COM","rememberMe":False}
r = s.post(login_url, json=data)
print(s.cookies)
print(r.json())

Having trouble converting cURL POST command to python requests

I am trying to convert a block of cURL to python requests. I get the following error when I do:
{'error': 'invalid_request', 'error_description': 'request is missing a required parameter or malformed.'}
What am I translating incorrectly?
curl
POST /identity/v1/oauth2/token HTTP/1.1
Host: api.sandbox.ebay.com
Authorization: Basic <B64-encoded-oauth-credentials>
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&code=<URL-decoded-auth-code>&redirect_uri=<your_redirect_uri>
my_call.py
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
a 'Authorization': f'Basic {<Base64 encoded value>}'
}
data = {
'grant_type': 'authorization_code',
'code': client_id # str,
'redirect_uri': url # str,
'scope': 'https://api.ebay.com/oauth/api_scope/sell.inventory.readonly',
}
def get_oath_token():
url = 'https://api.ebay.com/identity/v1/oauth2/token'
r = requests.post(url, headers=headers, data=data)
print(r.json())

Error 403 when calling the authentication in Office365 APIs of Azure AD

I'm making a web application to call Office365 API, and is using the authentication function of Azure AD. I am not having any progress since last week, and we suddenly got this error:
statuscode: 403,
body: '{"error":{"code":"ErrorAccessDenied","message":"Access is denied. Check credentials and try again."}}
Here is the Request that I sent
var request = {
url: url,
method: method,
json: (method === constants.GET || method === constants.DELETE) ? null : resource,
headers: {
'Authorization': credentials.tokenType + ' ' + credentials.accessToken,
'User-Agent': clientId,
'Accept' : 'application/json'
}
Could anyone explain how to fix this?

Resources