I am trying to upload a photo (jpg image) using the new Google Photos API.
I am able to get an uploadToken but when I try to create the media item I get the following error:
{
"newMediaItemResults": [
{
"uploadToken": "CAIS+QIAkor2Yr4JcvYMMx..... ",
"status": {
"code": 3,
"message": "NOT_IMAGE: There was an error while trying to create this media item."
}
}
]
}
Here is a snippet of my code:
import sys
import json
import requests
pic = 'image.jpg'
fname = 'read_write_token_creds.json'
with open(fname) as f:
data = json.load(f)
tok = data['access_token']
# Step 1 get an upload token
URL = 'https://photoslibrary.googleapis.com/v1/uploads'
headers = {
'Content-type': 'application/octet-stream',
'X-Goog-Upload-File-Name': pic,
'X-Goog-Upload-Protocol': 'raw',
'Authorization': 'Bearer ' + tok,
}
files = {'file': open(pic, 'rb')}
r = requests.post(URL, headers=headers, files=files)
upload_token = r.text
# Step 2
album_id = 'AG.....7u'
URL = 'https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate'
header = {
'Content-type': 'application/json',
'Authorization': 'Bearer ' + tok
}
payload = {
'albumId': album_id,
'newMediaItems': [
{
'description': 'Desc.',
'simpleMediaItem': { 'uploadToken': upload_token }
}
]
}
r = requests.post(URL, headers=header, data=json.dumps(payload))
When I look at r.text from the requests module, I receive the error message which was given at the top of he message.
This worked for me.
How to authenticate user see here https://developers.google.com/photos/library/guides/upload-media
def upload(service, file):
f = open(file, 'rb').read();
url = 'https://photoslibrary.googleapis.com/v1/uploads'
headers = {
'Authorization': "Bearer " + service._http.request.credentials.access_token,
'Content-Type': 'application/octet-stream',
'X-Goog-Upload-File-Name': file,
'X-Goog-Upload-Protocol': "raw",
}
r = requests.post(url, data=f, headers=headers)
print '\nUpload token: %s' % r.content
return r.content
def createItem(service, upload_token, albumId):
url = 'https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate'
body = {
'newMediaItems' : [
{
"description": "test upload",
"simpleMediaItem": {
"uploadToken": upload_token
}
}
]
}
if albumId is not None:
body['albumId'] = albumId;
bodySerialized = json.dumps(body);
headers = {
'Authorization': "Bearer " + service._http.request.credentials.access_token,
'Content-Type': 'application/json',
}
r = requests.post(url, data=bodySerialized, headers=headers)
print '\nCreate item response: %s' % r.content
return r.content
# authenticate user and build service
upload_token = upload(service, './path_to_image.png')
response = createItem(service, upload_token, album['id'])
Related
My audio for podcast and art for it on google drive, in doc says to make like this, but it returns 400 error
import requests
podcast_file = "https://drive.google.com/file/d/1w0IDXVotyHKEGSbBWUxEoDvaJQRsWCJO"
headers = {
'Authorization': 'Token here my token',
'Content-Type': 'application/json',
}
new_episode = {
"title":"Too many or too few?",
"description":"",
"summary":"",
"artist":"Muffin Man",
"tags":"",
"duration":23462,
"guid":"Buzzsprout788880",
"episode_number":1,
"season_number":1,
"explicit":False,
"private":False,
"email_user_after_audio_processed": False,
"audio_url": podcast_file,
"artwork_url": "https://drive.google.com/file/d/1xoNKAbTYX8GjVg0ZB_ekFUl8ljQICMZv"
}
url = 'https://www.buzzsprout.com/api/episodes.json'
req = requests.post(url, data=new_episode, headers=headers)
print(req.text)
print(req.status_code)
i'm trying to upload a zip file to Team Google Drive, but the file appears in my own Google drive, and not in the Team's folder. I have a permissions for the team's (shared) folder and I can upload files there manually. I'm able to obtain the access_token.This is my code:
import json
import requests
def get_token():
oauth = 'https://www.googleapis.com/oauth2/v4/token' # Google API oauth url
headers = {'content-type': 'application/x-www-form-urlencoded'}
data = {
'grant_type': 'refresh_token',
'client_id': '{CLIENT_ID}',
'client_secret': '{CLIENT_SECRET}',
'refresh_token': '{REFRESH_TOKEN}',
}
token = requests.post(oauth, headers=headers, data=data)
_key = json.loads(token.text)
return _key['access_token']
# Upload files to google drive using access token
def upload_to_drive(files):
token_key = get_token()
headers = {"Authorization": "Bearer " + token_key}
upload = requests.post(
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
headers=headers,
files=files
)
print(upload.text)
if __name__ == '__main__':
file = "my_folder.zip"
para = {
"name": file,
# "parents": [FOLDER_ID],
"parents": [{
"kind": "drive#file",
"driveId": "{TEAM_DRIVE_ID}",
"id": "{FOLDER_ID}",
"supportsAllDrives": True
}],
}
files_for_upload = {
'data': ('metadata', json.dumps(para), 'application/json; charset=UTF-8'),
'file': ('application/zip', open("./" + file, "rb"))
}
upload_to_drive(files_for_upload)
Any help is much appreciated!
Find a solution:
import json
import requests
def get_token():
oauth = 'https://www.googleapis.com/oauth2/v4/token' # Google API oauth url
headers = {'content-type': 'application/x-www-form-urlencoded'}
data = {
'grant_type': 'refresh_token',
'client_id': '{CL}',
'client_secret': '{CLIENT_SECRET}',
'refresh_token': '{REFRESH_TOKEN}',
}
token = requests.post(oauth, headers=headers, data=data)
_key = json.loads(token.text)
return _key['access_token']
# Upload files to google drive using access token
def upload_to_drive(files):
token_key = get_token()
headers = {"Authorization": "Bearer " + token_key}
upload = requests.post(
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&supportsAllDrives=true",
headers=headers,
files=files
)
print(upload.text)
if __name__ == '__main__':
file = "my_file.zip"
para = {
"name": file,
"parents": ['{FOLDER_ID}'],
}
files_for_upload = {
'data': ('metadata', json.dumps(para), 'application/json; charset=UTF-8'),
'file': ('application/zip', open("./" + file, "rb"))
}
upload_to_drive(files_for_upload)
supportsAllDrives should not be a part of metadata!
I'm trying to automate a process in which i have to download some brazilian fund quotes from Anbima (Brazil regulator). I have been able to work around the first steps to retrieve the access token but i don't know how to use the token in order to make requests. Here is the tutorial website https://developers.anbima.com.br/en/como-acessar-nossas-apis/.
I have tried a lot of thing but all i get from the request is 'Could not find a required APP in the request, identified by HEADER client_id.'
If someone could share some light. Thank you in advance.
import requests
import base64
import json
requests.get("https://api.anbima.com.br/feed/fundos/v1/fundos")
ClientID = '2Xy1ey11****'
ClientSecret = 'faStF1Hc****'
codeString = ClientID + ":" + ClientSecret
codeStringBytes = codeString.encode('ascii')
base64CodeBytes = base64.b64encode(codeStringBytes)
base64CodeString = base64CodeBytes.decode('ascii')
url = "https://api.anbima.com.br/oauth/access-token"
headers = {
'content-type': 'application/json'
,'authorization': f'Basic {base64CodeString}'
}
body = {
"grant_type": "client_credentials"
}
r = requests.post(url=url, data=json.dumps(body), headers=headers, allow_redirects=True)
jsonDict = r.json()
##################
urlFundos = "https://api-sandbox.anbima.com.br/feed/precos-indices/v1/titulos-publicos/mercado-secundario-TPF"
token = jsonDict['access_token']
headers2 = {
'content-type': 'application/json'
,'authorization': f'Bearer {token}'
}
r2 = requests.get(url=urlFundos, headers=headers2)
r2.status_code
r2.text
I was having the same problem, but today I could advance. I believe you need to adjust some parameters in the header.
Follows the piece of code I developed.
from bs4 import BeautifulSoup
import requests
PRODUCTION_URL = 'https://api.anbima.com.br'
SANDBOX_URL = 'https://api-sandbox.anbima.com.br'
API_URL = '/feed/fundos/v1/fundos/'
CODIGO_FUNDO = '594733'
PRODUCTION = False
if PRODUCTION:
URL = PRODUCTION_URL
else:
URL = SANDBOX_URL
URL = URL + API_URL + CODIGO_FUNDO
HEADER = {'access_token': 'your token',
'client_id' : 'your client ID'}
html = requests.get(URL, headers=HEADER).content
soup = BeautifulSoup(html, 'html.parser')
print(soup.prettify())
The sandbox API will return a dummy JSON. To access the production API you will need to request access (I'm trying to do this just now).
url = 'https://api.anbima.com.br/oauth/access-token'
http = 'https://api-sandbox.anbima.com.br/feed/precos-indices/v1/titulos-publicos/pu-intradiario'
client_id = "oLRa*******"
client_secret = "6U2nefG*****"
client_credentials = "oLRa*******:6U2nefG*****"
client_credentials = client_credentials.encode('ascii')
senhabytes = base64.b64encode(client_credentials)
senha = base64.b64decode(senhabytes)
print(senhabytes, senha)
body = {
"grant_type": "client_credentials"
}
headers = {
'content-type': 'application/json',
'Authorization': 'Basic b0xSYTJFSUlOMWR*********************'
}
request = requests.post(url, headers=headers, json=body, allow_redirects=True)
informacoes = request.json()
token = informacoes['access_token']
headers2 = {
"content-type": "application/json",
"client_id": f"{client_id}",
"access_token": f"{token}"
}
titulos = requests.get(http, headers=headers2)
titulos = fundos.json()
I used your code as a model, then I've made some changes. I've printed the encode client_id:client_secret and then I've copied and pasted in the headers.
I've changed the data for json.
I am trying to upload a file via Python requests and i receive an error code 400 (Bad request)
#Update ticket with upload of CSV file
header_upload_file = {
'Authorization': 'TOKEN id="' + token + '"',
'Content-Type': 'multipart/form-data'
}
files = {
'name': 'file',
'filename': open(main_path + '/temp/test.txt', 'rb'),
'Content-Disposition': 'form-data'
}
response = requests.post(baseurl + '/incidents/number/' + ticket_number + '/attachments/', headers=header_upload_file, data=files, verify=certificate)
If i try via Postman this is successfull using following code.
url = "https://<url>"
payload = "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"file\"; filename=\"C:\\Users\\<filename>\"\r\nContent-Type: text/csv\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--"
headers = {
'content-type': "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
'Authorization': "TOKEN id="3e9d095d-a47b-48b5-a0b8-ae8b8ad9ae74"",
'cache-control': "no-cache",
'Postman-Token': "bb155176-b1b8-47a6-8fb3-46f5740cf9e0"
}
response = requests.request("POST", url, data=payload, headers=headers)
print(response.text)
What do i wrong?
You should use the files parameter instead. Also, don't explicitly set Content-Type in the header so that requests can set it for you with a proper boundary:
header_upload_file = {
'Authorization': 'TOKEN id="' + token + '"'
}
response = requests.post(
baseurl + '/incidents/number/' + ticket_number + '/attachments/',
headers=header_upload_file,
files={'file': ('file', open(main_path + '/temp/test.txt', 'rb'), 'text/csv')},
verify=certificate
)
I want to update the title of a pull request and performing the below to achieve it :- (followed this doc https://developer.github.com/v3/pulls/#update-a-pull-request)
data = {"title": "New title"}
url='https://hostname/api/v3/repos/owner/repo/pulls/80'
token = 'my-token'
headers = {'Content-type': 'application/json', 'Accept': 'application/json', 'Authorization': 'token %s' % token}
resp = requests.patch(url, data=json.dumps(data), headers=headers)
print resp.json()
What am I missing ? Please help.
The following worked for me:
import requests
token = "my-token"
url = "https://api.github.com/repos/:owner/:repo/pulls/:number"
payload = {
"title": "New title"
}
r = requests.patch(url, auth=("username", token), json=payload)
print r.json()