I'm trying to make a get request to Azure DevOps.
I have the URL and the Personal_Access_Token. The URL was created following these intructions https://learn.microsoft.com/en-us/rest/api/azure/devops/git/items/get?view=azure-devops-rest-6.1&tabs=HTTP#definitions , and it is working fine in the browser. It is possible to see the information of the file that I'm targeting.
However, when I execute the request in python:
import requests
headers = {
'Authorization': 'Bearer myPAT',
}
response = requests.get('exampleurl.com/content', headers=headers)
I'm getting the 203 response...
I have also try other options following this link Python requests library how to pass Authorization header with single token without success. Including these headers:
personal_access_token_encoded = base64.b64encode(personal_access_token.encode('utf-8')).decode('utf-8')
headers={'Authorization': 'Basic '+personal_access_token_encoded}
headers={'Authorization': 'Basic '+personal_access_token}
But in both cases still having the same response.
For sure I'm not considering something. What could be missing?
For Azure DevOps API, you need to use Basic Auth instead of Baerear, providing only the PAT token encoded in base64.
Hi error feedback 203 is about your invalid token.
So what is the authorization type of your request call?
For pat headers = {'Authorization': 'Basic pat'}
For bearer token headers = {'Authorization': 'Bearer MYREALLYLONGTOKENIGOT'}
You could put your rest api in postman and click the code button at the right-side bar to overview the rest api into different script.
Related
I'm trying to test out some AWS APIs that are protected by Cognito. I found the first part on how to get the Json token but I can't figure out how to use the token correctly so I can authenticate on the API.
Here's my code :
import boto3 as boto3;
import requests
username='test#gmail.com'
password='test1234567'
client = boto3.client('cognito-idp')
response = client.initiate_auth(
AuthFlow='USER_PASSWORD_AUTH',
AuthParameters={
"USERNAME": username,
"PASSWORD": password,
},
ClientId='12121212121212',
)
token = response['AuthenticationResult']['AccessToken']
#print("Log in success")
#print("Access token:", response['AuthenticationResult']['AccessToken'])
#print("ID token:", response['AuthenticationResult']['IdToken'])
url = 'https://XXXXXXXX.execute-api.eu-west-1.amazonaws.com/Prod/incidents'
#print('url:', url)
#response = requests.get(url, headers={'authorization': token })
#print('GET:', response.status_code)
head = {'Authorization': token}
response = requests.get(url, headers=head)
print(response.content)
I'm getting the following error message :
b'{"message":"Authorization header requires \'Credential\' parameter. Authorization header requires \'Signature\' parameter. Authorization header requires \'SignedHeaders\' parameter. Authorization header requires existence of either a \'X-Amz-Date\' or a \'Date\' header. Authorization=
Ok so I found the problem and it's working fine now, 2 things were wrong :
The endpoint was wrong - AWS doesn't send a correct error message (!)
The request has to be sent with response['AuthenticationResult']['IdToken']
Please make sure you have selected Cognito or IAM in your API Gateway. From the error message it seems you have selected IAM for protecting the API.
Check the Authorization header's name which you configured for your Cognito Authorizer. You need to use same header name while passing the Cognito token.
If you have configured OAuth scopes in API Gateway side, then you must use access token. And no scope is configured then you can use ID token for authorization.
That said, you can try from Postman application for testing purpose.
I want to do an API call using request of my user in Calendly like Documentation but I can't do it. I don't know if I need something else in my code, thanks.
import requests, json
api_key = 'aaaaaaaaa'
header = {
'Authorization' : api_key
}
response = requests.get('https://api.calendly.com/users/me/', headers= header)
print(response)
print(response.json())
I'm getting a 401 response:
<Response [401]> {'title': 'Unauthenticated', 'message': 'The access token is invalid'}
I suspect you're trying to use the API Key for API v2. The API Key only works with Calendly's legacy API v1. API v2 supports the following two authorization schemes:
OAuth authorization code flow, or
Personal Access Tokens.
See developer.calendly.com/getting-started for more details.
If you are using a personal token with the API v2, you need to prepend Bearer before your token.
Example:
header = {
'Authorization': f'Bearer {api_key}'
}
Source:
https://calendly.stoplight.io/docs/api-docs/YXBpOjM5NQ-calendly-api
I'm currently using the Python Requests module to add videos to a playlist created by me. On the docs for playlistItems.insert, it says authorization is required with one of three possible scopes. I have created an OAUTH2.0 credential token in my project's credential panel and set the scope correctly. Currently I'm trying to pass the credential as follows:
payload = {
'access_token': [My Client ID],
'part': 'snippet'}
new_vid = requests.post(f'{base_url}playlistItems', params=payload)
When executing the code, I get the following error message:
"message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project."
Am I passing the authorization token in the correct place, or should I be passing it somewhere else in the POST request?
You can pass the Authorization token as a header parameter. Check the example below:
import requests
headers = {
'Authorization': 'Bearer [YOUR_ACCESS_TOKEN]',
'Accept': 'application/json',
'Content-Type': 'application/json',
}
params = (
('key', '[YOUR_API_KEY]'),
('part','snippet')
)
response = requests.post('https://youtube.googleapis.com/youtube/v3/playlistItems', headers=headers, params=params)
I'm tying to get the data from the Cloudhub API which resides on Mulesoft.
I tried to access through postman (With the same Client Credentials - Bearer Authorization) and it's working fine (I can able to get the result with proper get requests).
But when I tried to do the same with Python requests library I ran into issues. Here is my piece of code:
import requests
import json, os
CLIENT_ID = os.environ['CLIENT_ID']
CLIENT_SECRET = os.environ['CLIENT_SECRET']
grant_type = 'client_credentials'
body_params = {'grant_type' : grant_type}
headers = {'Accept': '*/*',
'Cache-Control':'no-cache',
'Accept-Encoding': 'gzip, deflate',
'Content-Type':'application/json, application/x-www-form-urlencoded',
'Connection': 'keep-alive'}
url='https://<domain-name>-api.us-w2.cloudhub.io/api/token'
response = requests.post(url, data=body_params, auth = (CLIENT_ID, CLIENT_SECRET), headers= headers)
token_raw = json.loads(response.text)
print(token_raw)
Result: {'error': 'Authentication denied.'}
All I need to know is
How it's working fine with Postman but why I'm not able to connect with python code?
Is there anything I've to change in my code or any additional information needed for this request? or am I passing the correct endpoint in receiving the access token for Cloudhub API?
Please post your suggestions or any documentation that I need to refer.
Hope the information that I gave is clear and Thanks in Advance !!
I found the answer of my own question. I can get it from the postman itself.
Here is my code for API Call with Python.
import http.client
import os
conn = http.client.HTTPSConnection("<domain-name>-api.us-w2.cloudhub.io")
payload = ''
headers = {
'client_id': os.environ['CLIENT_ID'],
'client_secret': os.environ['CLIENT_SECRET']
}
conn.request("GET", "/api/<Query that you want to pass - endpoint>", payload, headers)
response = conn.getresponse()
resp_data = response.read()
print(resp_data.decode("utf-8"))
The URL is incorrect. To call CloudHub REST API you need to obtain a bearer token from Anypoint Platform REST API. The URL mentioned looks to for some application deployed in CloudHub, not from the platform APIs. This is the same method than to get the bearer token to use in Anypoint MQ Admin API. It looks like you are trying to use the Anypoint MQ Broker API, which is an Anypoint MQ specific token.
Example in Curl to get an Anypoint Platform token:
$ curl -H "Content-Type: application/json" -X POST -d '{"username":"joe.blogs","password":"sample.password"}' https://anypoint.mulesoft.com/accounts/login
{
"access_token": "f648eea2-3704-4560-bb46-bfff79712652",
"token_type": "bearer",
"redirectUrl": "/home/"
}
Additionally the Content-type of your example seems incorrect because it has 2 values.
I'm sure the Postman request is different for it to work, or maybe it works only for the Anypoint MQ Broker API.
I am trying to use Python requests to use the API of Adform. How do I exactly include the access token (which I could successfully retrieve already) in my get request header?
I understand the API is based on OAuth2, and I am trying to use Client Credentials authorization. Here is the API docs: http://api.adform.com/help/guides/authorization-guide#consumingapis
I really can't tell the exact format of my header from this small amount of information.
I've tried:
requests.get(url, headers={'Authorization': 'MY_TOKEN_HERE'}
requests.get(url, headers={'Authorization': 'Bearer MY_TOKEN_HERE'}
requests.get(url, headers={'Authorization': 'access_token MY_TOKEN_HERE'}
None works unfortunately, all return <401> unauthorized. My access token is valid for sure.
requests.get(url, headers={'Authorization': 'Bearer MY_TOKEN_HERE'} should work, as long as MY_TOKEN_HERE is valid.
You may use requests_oauth2client to format the header properly with an AuthHandler:
from requests_oauth2client import BearerAuth
requests.get(url, auth=BearerAuth("MY_TOKEN_HERE"))
And you may even use it to get the access token easily, and have a requests Session that will automatically get the token as required and cache it as long as it is valid from next API calls:
from requests_oauth2client import OAuth2Client, OAuth2ClientCredentialsAuth
import requests
# define your OAuth2 client, with a Token Endpoint URL, a Client ID and a secret.
client = OAuth2Client("https://url.to.the.token.endpoint", auth=("CLIENT_ID", "CLIENT_SECRET"))
# use a session to benefit from token caching
session = requests.Session()
session.auth = OAuth2ClientCredentialsAuth(client, scope="YOUR_SCOPE"))
resp = session.get(url) # an access token will be obtained as required at this point before the API call is done
this one
curl --location --request GET
'https://api.adform.com/v1/seller/publishers' \
--header 'Authorization: Bearer MY_TOKEN_HERE'