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

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.

Related

Twitter Ads API Unauthorized Issue

I am trying to access twitter ads API for fetching ad analytics. So when I tried to access the API : https://ads-api.twitter.com/11/stats/accounts/18ce55gz0e6?entity=LINE_ITEM&entity_ids=8u94t&start_time=2017-05-19&end_time=2017-05-26&granularity=TOTAL&placement=ALL_ON_TWITTER&metric_groups=ENGAGEMENT and gave Authorization : Bearer <bearer_token> as header. I got an Unauthorized error. This is the error that I got:
{
"errors": [
{
"code": "UNAUTHORIZED_ACCESS",
"message": "This request is not properly authenticated"
}
],
"request": {
"params": {}
}
}
Then I came across twitter-ads library https://github.com/twitterdev/twitter-python-ads-sdk
but I did'nt understand how to fetch campaign analytics using this. Can anyone please mention any solution?

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

Invalid Credentials Error when updating file to Google drive API

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.

What is wrong with my patch request to the Connectwise Rest API?

I've got a question about the Rest API for Connectwise. I've been doing get and post requests with no issue, but when I do a patch request I get a 400 response with 'field value is invalid' message regardless of what I try. I'm on 2016v1 and using the Rest API making calls from Python with the requests library.
The Rest API documentation says the following object is supposed to be passed in the body, but I haven't a clue what values are supposed to go with these keys:
{
op (string, optional),
path (string,optional),
value (string,optional)
}
I've tried dozens of calls including with the following bodies:
{'summary': 'updatedsummarytext'}
{'value': {'summary': 'updatedsummarytext'}}
{'op': {'summary': 'updatedsummarytext'}}
I have only gotten the following response so far:
<Response [400]>
{
"code": "InvalidObject",
"message": "operations object is invalid",
"errors": [
{
"code": "InvalidField",
"message": "The field value is invalid.",
"resource": "operations",
"field": "value"
}
]
}
Is their a specific value that connectwise is expecting for the op or value keys, or is there something I'm missing unique to Patch rest api calls?
The PATCH calls at a basic level use RFC6902.
Consider the following (simplified) Ticket document:
{
"summary": "Initial Ticket Summary",
"id": 1,
"company": {
"id": 5
},
"board": {
"id": 10
}
}
If you wish to update the summary field, your PATCH request JSON would look like this:
[
{"op": "replace", "path": "/summary", "value": "Updated Summary"}
]
Hope this helps.

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