Twitter Ads API Unauthorized Issue - python

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?

Related

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.

YouTube API v3 - Python - how to batch insert playlistItems

I've been using the Youtube API to add multiple playlistItems to playlists on my profile, but doing so with loops tends to use up my daily request quota and I've hundreds to add.
I'm sending <50 video IDs per batch
the video IDs are all valid, and can be added succesfully one at a time
The new_batch_http_request method seems to be the solution but roughly 1 in every 4 video ids within the batch ends up failing. On Googling the problem it might be related to the position leading to overwrites?
Using this example, the first and third items were successful but the 2nd failed:
from Google import Create_Service
CLIENT_SECRET_FILE = 'client_secret_file.json'
API_NAME = 'youtube'
API_VERSION = 'v3'
SCOPES = ['https://www.googleapis.com/auth/youtube',
'https://www.googleapis.com/auth/youtube.force-ssl']
service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES)
playlistItemsList = ['eDTnKLqFuYU', 'TT7plfxWK6E','oMbL_7lpD1w']
batch = service.new_batch_http_request(callback=insert_video)
for videoId in playlistItemsList:
batch.add(
service.playlistItems().insert(part="snippet",
body={"snippet": {
"playlistId": "PLs7sB4wt2IftzifT5G4cdjQlXZQpEk2Go",
"position": 0,
"resourceId": {"kind": "youtube#video", "videoId": videoId},
}
},
),
)
request = batch.execute()
Using the callback function I can see that the failed attempts are returning:
<HttpError 500 when requesting https://youtube.googleapis.com/youtube/v3/playlistItems?part=snippet&alt=json returned "Internal error encountered.". Details: "Internal error encountered.">
{
"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"
}
}
Is there a way to sequentially add to playlist but utilising a batch method?
I noticed a serialise batch request within Google API docs - could this be what I'm looking for?
https://googleapis.github.io/google-api-python-client/docs/epy/googleapiclient.http.BatchHttpRequest-class.html#_execute
My code is based on this:
https://learndataanalysis.org/copy-videos-from-any-youtube-playlist-to-your-own-playlist-with-python-and-youtube-api/

Python google api reading with urllib and json

My Code is very short but it is not working but in youtube videos it works
import urllib.request
import json
key = "AIzaSyCyTALBjNAEp-Vr5GkilEnLzH0y1Tw6SC4"
data = urllib.request.urlopen("www.googleapis.com/youtube/v3/channels?part=statistics&forUsername=pewdiepie&key="+key).read()
subs = json.loads(data)['items'][0]["statistics"]['subscriberscount']
print(subs)
You need to create you own API key
https://www.googleapis.com/youtube/v3/channels?part=statistics&forUsername=pewdiepie&key=AIzaSyCyTALBjNAEp-Vr5GkilEnLzH0y1Tw6SC4
shows
"error": {
"code": 403,
"message": "YouTube Data API v3 has not been used in project 195563281908 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/youtube.googleapis.com/overview?project=195563281908 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.",
"errors": [
{
"message": "YouTube Data API v3 has not been used in project 195563281908 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/youtube.googleapis.com/overview?project=195563281908 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.",
"domain": "usageLimits",
"reason": "accessNotConfigured",
"extendedHelp": "https://console.developers.google.com"
}
],
"status": "PERMISSION_DENIED"
}
}
Here you can find how to create own API key:
https://developers.google.com/youtube/v3/getting-started

Google Fusion Tables POST requests return 400 Bad Request using Python

I am trying to create a script Python script that allows me to both Read a Google Fusion Table and to import rows in to it. I have been working with the sample code found at https://developers.google.com/fusiontables/docs/samples/python to try and develop an understanding of how to work with fusion tables.
My problem is that the samples in here that involve making POST requests all result in a "400 Bad Request" being returned. GET requests work just fine though. As far as I can tell the requests follow the API style guide. Why would this be failing?
EDIT:
Specifically the request returns:
400 Bad Request
{
"error": {
"errors": [
{
"domain": "global",
"reason": "parseError",
"message": "Parse Error"
}
],
"code": 400,
"message": "Parse Error"
}
}

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