Invalid Credentials Error when updating file to Google drive API - python

I have been trying to replace files using google API only with the Python HTTPS module. Can somebody please help me with how I can replace the file only with an HTTPS module?
import sys
import json
import requests
import sys
Acesstoken = ""
params = {
"grant_type": "refresh_token",
"client_id": "xxx",
"client_secret": "xxxx",
"refresh_token": "xxxx"
}
authorization_url = "https://www.googleapis.com/oauth2/v4/token"
r = requests.post(authorization_url, data=params)
if r.ok:
token = str((r.json()['access_token']))
Refreshtoken = Acesstoken + token
else:
print('Failed')
sys.exit()
headers = {
"Authorization": "Bearer " + str(Acesstoken),
}
metadataF= {
'name': "Test",
'parents':["1vXn346cBsarvkPthqtI1OLzsMzeQQlBX"]
}
files = {
'data':('metadata', json.dumps(metadataF), 'application/json; charset=UTF-8'),
'file': open("./credentials.json", "rb"),
}
r2= requests.post(
"https://www.googleapis.com/upload/drive/v3/files/XXXXXXXX?uploadType=multipart",
headers= headers,
files= files
)
print(r2)
I only want to use Python's Https Module only. I don't want to use google client library. Please help me if this is possible.
Error
<Response [401]> with this ` { "error": { "errors": [ { "domain": "global", "reason": "authError", "message": "Invalid Credentials", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Invalid Credentials" }

<Response [401]> with this ` { "error": { "errors": [ { "domain": "global", "reason": "authError", "message": "Invalid Credentials", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Invalid Credentials" }
Invalid Credentials means that your token has expired. Access tokens are only valid for an hour. Refresh tokens are only valid for seven days if your app is still in testing.

As documented here the error 401 error: Invalid credentials is related to:
... the access token you're using is either expired or invalid. This error can also be caused by missing authorization for the requested scopes ...
If the token works with another type of request you may want to check the scopes.

Related

Creating Jira issue with REST API

Having issues with trying to create an issue with Jira through the APIs, below is a sample of my code. We are using enterprise jira, I have to replace certain sections with so I hope it wont effect your ability to provide help.
from requests.auth import HTTPBasicAuth
import requests
user = '<ID>'
password = '<password>'
url = 'https://<enterprise>jira.<domain>.com/projects/<MYKEY>/rest/api/3/issue'
headers = {
'Content-Type': 'application/json',
}
json_data = {
"fields": {
"project": {
"key": "<MYKEY>"
},
"summary": "Creating From Collection",
"description": {
"type": "doc",
"version": 1,
"content": [
{
"type": "paragraph",
"content": [
{
"type": "text",
"text": "This is an autogenerated issue from a demo."
}
]
}
]
},
"issuetype": {
"name": "Task"
}
}
}
response = requests.post(
url,
headers=headers,
json=json_data,
verify=False,
auth=(user, password),
)
I get error code 405 and the following message when running print(response.text):
<!doctype html>HTTP Status 405 – Method Not Allowedbody {font-family:Tahoma,Arial,sans-serif;} h1, h2, h3, b {color:white;background-color:#525D76;} h1 {font-size:22px;} h2 {font-size:16px;} h3 {font-size:14px;} p {font-size:12px;} a {color:black;} .line {height:1px;background-color:#525D76;border:none;}HTTP Status 405 – Method Not AllowedType Status ReportMessage HTTP method POST is not supported by this URLDescription The method received in the request-line is known by the origin server but not supported by the target resource.Apache Tomcat/8.5.78
Im sure I'm doing something wrong so any help will be appreciated.
Also I have verified I have the right access by manually going to the project and creating an issue.
Your URL is wrong. For creating a Jira issue you want to use the create issue endpoint.
For server/datacenter:
url = 'https://<enterprise>jira.<domain>.com/rest/api/2/issue'
For cloud:
url = 'https://<enterprise>jira.<domain>.com/rest/api/3/issue'
You need to use a POST request to either of these endpoints.

Discord API "Cannot send an empty message"

I'm trying to manually respond to a discord API call by getting the token from the logs of my API but when i send the request, it responds with
<Response [400]>
{"message": "Cannot send an empty message", "code": 50006}
Code is below:
import requests
application_id = "9999999999032"
payload = {"type": 4,
"data": {"content": "Congrats on sending your command!"}}
interaction_token = "aW50****lm"
headers = {'content-type': 'application/json'}
r = requests.patch(f"https://discord.com/api/v9/webhooks/{application_id}/{interaction_token}/messages/#original", headers=headers, json=payload)
print(r)
print(r.text)
Link to docs https://discord.com/developers/docs/interactions/receiving-and-responding#interaction-response-object-interaction-callback-type
I haven't tested your code yet, but I think the problem is in the payload variable, instead of doing this:
{
"type": 4,
"data": {
"content": "Congrats on sending your command!"
}
}
Do this:
{
"type": 4,
"content": "Congrats on sending your command!"
}
If it doesn't work, I don't know how to fix it.

Elastic search Api

Hey Stackoverflow fam,
I am working on an API which pulls requests from elastic search tool and displays it.
I am trying to pull data using get request
import requests
import json
payload = {
"query": {
"match": {
"metric": "metric_name"
}
}
}
url = "https://url_name:9200/siren-kinesis*/_search"
payload = json.dumps(payload)
print(type(payload))
headers = {
'Content-Type': 'application/json',
}
result = requests.get(url=url,data=payload,headers=headers,auth=("test#example.com","*"))
print(result.json())
and getting the following error
{
"error": {
"root_cause": [
{
"type": "security_exception",
"reason": "unable to authenticate user [test#example.com] for REST request [/_search]",
"header": {
"WWW-Authenticate": "Basic realm=\"security\" charset=\"UTF-8\""
}
}
],
"type": "security_exception",
"reason": "unable to authenticate user [test#example.com] for REST request [/_search]",
"header": {
"WWW-Authenticate": "Basic realm=\"security\" charset=\"UTF-8\""
}
},
"status": 401
}
I am Basic Auth .i.e. passing username and password for authorization.
Can somebody help me ?
In the case of Basic Auth in any request, if you're requesting via postman you can provide the credentials in the Authentication tab. But In the case of Code/Console/Browser, the certificates must be given in the request URL.
e.g.
https://username:password#URL
https://admin:admin#www.the-internet.herokuapp.com/basic_auth

python yt api "The request is missing a valid API key."

im using the youtube api in python, i using this code :
r = requests.get('https://www.googleapis.com/youtube/v3/videos')
print(r.text)
and i get this output :
{
"error": {
"code": 403,
"message": "The request is missing a valid API key.",
"errors": [
{
"message": "The request is missing a valid API key.",
"domain": "global",
"reason": "forbidden"
}
],
"status": "PERMISSION_DENIED"
}
}
Process finished with exit code 0
i already have my api key so my question is how do i add this api key to the GET request and make this work
The API key should be added as a GET parameter called key, like so:
r = requests.get('https://www.googleapis.com/youtube/v3/videos?key=YOUR_API_KEY&id=7lCDEYXw3mM&...')
print(r.text)
The documentation has a few more examples.

Trying to delete a post using Blogger API returns "not found" error

Sending a DELETE request to Blogger REST API (v3.0), I'm trying to delete a post using delete method. For this I use the following code:
api_uri = 'https://www.googleapis.com/blogger/v3/blogs/%s/posts/%s' % (blogId, postId)
result = urlfetch.fetch(url=api_uri,
method=urlfetch.DELETE,
headers={'Authorization' : oauth_token})
self.response.out.write(result.content)
But the server returns:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "notFound",
"message": "Not Found"
}
],
"code": 404,
"message": "Not Found"
}
}
However, I can retrieve information about this post, using the following code:
api_uri = 'https://www.googleapis.com/blogger/v3/blogs/%s/posts/%s' % (blogId, postId)
result = urlfetch.fetch(url=api_uri,
headers={'Authorization' : oauth_token})
self.response.out.write(result.content)
At this moment, I can't understand what am I doing wrong — the request is authorized, the blogId and postId are correct — but anyway, the server returns "not found" error.
If you know how to solve this problem or you can give useful advice — help me please. Thank you for your time and consideration of this matter.
UPD 1: If I send requests to the following URLs:
# https://www.googleapis.com/blogger/v3/users/{userID}
# https://www.googleapis.com/blogger/v3/users/self
The server also returns:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "notFound",
"message": "Not Found"
}
],
"code": 404,
"message": "Not Found"
}
}
UPD 2: I forgot to say that I'm using OAuth 2.0 for Server to Server Applications. Thus, to get authorization token, I send request to https://accounts.google.com/o/oauth2/token using the following JWT Claim Set:
jwt_claim_set = {
'iss' : '{id}#developer.gserviceaccount.com',
'scope' : 'https://www.googleapis.com/auth/blogger',
'aud' : 'https://accounts.google.com/o/oauth2/token',
'exp' : expire,
'iat' : timestamp
}
The server returns:
{
"access_token" : "1/8xbJqaOZXSUZbHLl5EOtu1pxz3fmmetKx9W8CV4t79M",
"token_type" : "Bearer",
"expires_in" : 3600
}
And define variable oauth_token, using:
data = simplejson.loads(result.content)
oauth_token = data['token_type'] + ' ' + data['access_token']
Are you sure that you're using OAuth2 properly? It seems to me that you're not properly logged in, and that's why you're getting those errors.
Try those same queries using Google OAuh2 Playground (https://code.google.com/oauthplayground/) and see what happens.

Categories