Delete contact function in People API not work: Method: people.deleteContact - python

Now i try to use python to code one CMS project for contacts, but i have some problems.
I code this def but it is not work with google people API.
https://developers.google.com/people/v1/contacts
The logs
File "/Users/nguyenngoclinh/.conda/envs/1z_vietnam/lib/python3.7/site-packages/googleapiclient/http.py", line 907, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 404 when requesting https://people.googleapis.com/v1/%7B'people/c9194159806299427121'%7D:deleteContact?alt=json returned "Not Found">
delete fuction is bellow
def delete_contacts_with_resourceName(creds,http,number_of_contact):
# Call the People API
service = build('people', 'v1', credentials=creds)
print('Ban dang xoa', number_of_contactcontact, 'contacts')
results = service.people().connections().list(
resourceName='people/me',
pageSize=number_of_contactofcontact,
personFields='names,emailAddresses,phoneNumbers,emailAddresses,addresses').execute()
service = discovery.build('people', 'v1', http=http,
discoveryServiceUrl='https://people.googleapis.com/$discovery/rest')
connections = results.get('connections', [])
for person in connections:
abcd = person.get('resourceName')
service.people().deleteContact(resourceName={abcd}).execute()
But the creat contact def bellow also work.
def creat_a_google_contact(http):
# POST / v1 / people: createContact
# HTTP / 1.1
# Body: {"names": [{"givenName": "John", "familyName": "Doe"}]}
# Host: people.googleapis.com
service = discovery.build('people', 'v1', http=http,
discoveryServiceUrl='https://people.googleapis.com/$discovery/rest')
service.people().createContact(body={
"names": [
{
'givenName': "Nguyen Ngoc Linh",
"familyName": "29N2359 BMW 325i"
}
],
"phoneNumbers": [
{
'value': "0979955664"
}
],
"emailAddresses": [
{
'value': "bk.nguyenlinh#gmail.com"
}
],
"addresses": [
{
"streetAddress": "So 1 ngo 85 Lang Ha",
"extendedAddress": "Ba Dinh",
"city": "Ha Noi",
"region": "Ha Noi",
"postalCode": "10000",
"country": "Vietnam",
"countryCode": "84"
}
]
}).execute()
The def main, please anyone help me
def main():
creds = get_credentials(FLOW)
# print_list_google_contact_with_number_of_contacts(creds,1000)
http=get_http(creds)
#creat_a_google_contact(http)
# print_result(creds)
delete_contacts_with_resourceName(creds,http,1000)
#print_resourceName(creds, 2000)

Resource name is not formatted correctly:
If you try deleting the contact via Try this API from this page, you will notice that the URL to access has this shape:
https://people.googleapis.com/v1/people/c7142462727258425368:deleteContact
Where people/c7142462727258425368 is the contact's resourceName. That is to say, the resource name does not have single quotes (' ') nor brakets ({ }) around it. Since the resource name is not probably formatted in the URL, the API is not recognizing it, causing the 404 error.
That's what's failing in your request:
https://people.googleapis.com/v1/%7B'people/c9194159806299427121'%7D:deleteContact
To fix this, just remove the brackets around abcd when you provide it as resource name. It should be like this:
service.people().deleteContact(resourceName=abcd).execute()
Reference:
Method: people.deleteContact

Related

Add new contact in Xero using python FASTAPI

I am trying to add a new contact in Xero using python FASTAPI:
define a new contact
contact = {
"Contacts": [
{
"Name": "24 locks",
"FirstName": "Ben",
"LastName": "Bowden",
"EmailAddress": "ben.bowden#24locks.com",
"ContactPersons": [
{
"FirstName": "John",
"LastName": "Smith",
"EmailAddress": "john.smith#24locks.com",
"IncludeInEmails": "true"
}
]
}
]
}
Call xero API
get_url = 'https://api.xero.com/api.xro/2.0/Contacts'
response = requests.post(get_url,
headers = {
'Authorization': 'Bearer ' + access_token,
'Xero-tenant-id': xero_tenant_id,
'Accept': 'application/json'
},
data = contact
)
json_response = response.json()
I get the following error:
{'ErrorNumber': 17, 'Type': 'NoDataProcessedException', 'Message': 'No data has been processed for this endpoint. This endpoint is expecting Contact data to be specifed in the request body.'}
Someone can help please ?
You can assume that access_token and xero_tenant_id are correct as I am using them for other methods and they works fine.
Thanks
Try to use json = contact instead of data = contact or set header 'Content-Type': 'application/json'
Because
data for dict When not specified content-type, The default is application/x-www-form-urlencoded,

getting status code from google admin sdk

I am calling to google admin sdk. I am successfully creating users and everything is working fine. I started testing the project and when I create a duplicate user the program crashes. Can you help me get the status code response from google so I can prevent my code from crashing?
in google im using the user.insert method
Error from creating duplicate user
googleapiclient.errors.HttpError: <HttpError 409 when requesting
https://admin.googleapis.com/admin/directory/v1/users?alt=json returned
"Entity already exists.". Details: "Entity already exists.">
So how do i capture the 409, or a 200 or any other code that would come across?
def create_google_user(first_name, last_name, department):
# all the set up code from google here.
new_email = first_name + '.' + last_name + '#company.com'
new_user = {
"name": {
"familyName": last_name, # Last name
"givenName": first_name, # First name
},
"password": "random_PassWord",
"primaryEmail": new_email,
"suspended": False,
"changePasswordAtNextLogin": True,
"organizations": [
{
"department": department
}
],
"phones": [
{
"value": "1997915801",
"type": "work"
}
],
}
result = service.users().insert(body=new_user).execute()
print('Result: ', result)
print 'User Created'

Invalid JSON payload received. Unknown name at 'requests[1].paste_data.data': Cannot find field

UPDATE:
I used the api explorer on the google bactch update page and was able to successfully update the spreadsheet but when I replicate this in my code I am still getting an error. The API explorer did work with the json format.
<HttpError 400 when requesting
Invalid JSON payload received. Unknown name "value_input_option" at 'requests[0]': Cannot find field.
Invalid JSON payload received. Unknown name "data" at 'requests[0]': Cannot find field.">
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']
creds =
ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
service = discovery.build('sheets', 'v4', credentials=creds)
client = gspread.authorize(creds)
# find workbook by name and open the first sheet
# make sure you use the right name here
sheet = client.open("forklift").sheet1
# extract and print all of the values
# list_of_hashes = sheet.get_all_records()
spreadsheet_id = '112345'
batch_update_spreadsheet_request_body = {
"requests": [
{
"valueInputOption": "RAW",
"data": [
{
"majorDimension": "ROWS",
"range": "43:48",
"values": [
["www.colossalpoint.com","colossal point llc"]
]
}
]
}
],
"includeSpreadsheetInResponse": True,
"responseIncludeGridData": True
}
request = service.spreadsheets().batchUpdate(spreadsheetId=spreadsheet_id,
body=batch_update_spreadsheet_request_body)
response = request.execute()

Adding a new spreadsheet in an existing workbook raises HttpError "Unknown name requests"

I'm done building the Google Sheets service with the code snippet shown below and I would like to know how to create a new spreadsheet (aka tab) inside an already existing Google Sheet (workbook) with Python.
credentials = get_credentials(client_secret_file_path)
service = build('sheets', 'v4', credentials=credentials)
add_tab_request = {"requests": {"addSheet": {"properties": {"title": "New Tab"}}}}
request = service.spreadsheets().values().batchUpdate(spreadsheetId=<google_sheet_id>, body=add_tab_request)
Executing this code gives an HttpError:
Invalid JSON payload received. Unknown name "requests": Cannot find field.
The full error:
googleapiclient.errors.HttpError:
https://sheets.googleapis.com/v4/spreadsheets//values:batchUpdate?alt=json
returned "Invalid JSON payload received. Unknown name "requests": Cannot find field.">`
I did a lot of Google searching, but could not find a solution to this problem. I did not find this in the Google Sheets API v4 official documentation either. Why does not my request work?
After #SiHa's suggestion, this code worked for me. Hope this helps someone in future.
credentials = get_credentials(client_secret_file_path)
service = build('sheets', 'v4', credentials=credentials)
add_tab_request = {"requests": {"addSheet": {"properties": {"title": "New Tab"}}}}
request = service.spreadsheets().batchUpdate(spreadsheetId=<google_sheet_id>, body=add_tab_request)
Note that I had to remove the values() part from the API call.
You can add sheets in two ways:
at creation time, using the sheets.create method
at any time using the sheets.batchUpdate method
Below you have a snippet demonstrating both and working on my PC (python 3.6)
import os
import pickle
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
SCOPES = ['https://www.googleapis.com/auth/spreadsheets', ]
if not os.path.exists('credentials.dat'):
flow = InstalledAppFlow.from_client_secrets_file('client_id.json', SCOPES)
credentials = flow.run_local_server()
with open('credentials.dat', 'wb') as credentials_dat:
pickle.dump(credentials, credentials_dat)
else:
with open('credentials.dat', 'rb') as credentials_dat:
credentials = pickle.load(credentials_dat)
if credentials.expired:
credentials.refresh(Request())
spreadsheet_sdk = build('sheets', 'v4', credentials=credentials)
# we create a new sheet at creation time of the spreadsheet
create_body = {
'properties': {
'title': 'Newly created sheet',
'locale': 'en_US',
},
'sheets': [
{
'properties': {
'sheetId': 0,
'title': "Created at creation time",
'index': 0,
'sheetType': 'GRID',
'gridProperties': {
'rowCount': 2,
'columnCount': 2,
},
},
}
]
}
new_google_spreadsheet = spreadsheet_sdk.spreadsheets().create(body=create_body).execute()
# we add a sheet to an existing spreadsheet
add_sheet_params = {
'spreadsheetId': new_google_spreadsheet['spreadsheetId'],
'body': {
'requests': [
{
'addSheet': {
'properties': {
'sheetId': 1,
'title': "Added later",
'index': 0,
'sheetType': 'GRID',
'gridProperties': {
'rowCount': 2,
'columnCount': 2,
},
}
}
}
],
'includeSpreadsheetInResponse': False
}
}
new_sheet_add = spreadsheet_sdk.spreadsheets().batchUpdate(**add_sheet_params).execute()
print(new_sheet_add)
Here is what worked from me. I leveraged Google docs (https://developers.google.com/sheets/api/guides/batchupdate#example) & updated for the adding sheet use case
service = build('sheets', 'v4', credentials=creds)
# Create new sheet
requests = []
# Create a new spreadsheet.
requests.append({
'addSheet': {
'properties': {
'title': 'Findings',
'tabColor': {
'red': 0.44,
'green': 0.99,
'blue': 0.50
}
}
}
})
# Add additional requests (operations) ...
body = {
'requests': requests
}
response = service.spreadsheets().batchUpdate(
spreadsheetId=SAMPLE_SPREADSHEET_ID,
body=body).execute()

openstack cannot retrieve authentication token from API

I am trying to retrieve the authentication token from the API using requests library from python. Here is the attempt I have made so far:
def get_token():
data = {
"auth" : {
"identity" : {
"methods" : [ "password" ],
"password": {
"user" : {
"name" : OS_USERNAME,
"domain": { "name": "Default" },
"password": OS_PASSWORD
}
}
}
}
}
r = requests.post(
OS_AUTH_URL+'/auth/tokens',
headers = HEADERS,
json = data, # https://stackoverflow.com/questions/9733638
verify = False
)
print(r.content)
j = json.loads(r.content)
return j['token']['user']['id']
I get token in the response :
{
"token": {
"issued_at": "2018-07-03T11:03:59.000000Z",
"audit_ids": [
"Fg1ywtZBQ1CkigCw70If9g"
],
"methods": [
"password"
],
"expires_at": "2018-07-03T12:03:59.000000Z",
"user": {
"password_expires_at": null,
"domain": {
"id": "default",
"name": "Default"
},
"id": "e0dc5beb383a46b98dad824c5d76e719",
"name": "admin"
}
}
}
However, when I am reusing this token to get, for instance, the list of projects :
def get_tenantID():
r = requests.get(
OS_AUTH_URL+'/auth/projects',
headers = HEADERS,
verify = False
)
return r
r = get_token()
HEADERS['X-Auth-Project-Id'] = 'admin'
HEADERS['X-Auth-Token'] = r
r = get_tenantID()
I get this error as if I would not be authenticated:
<Response [401]>
{"error": {"message": "The request you have made requires authentication.", "code": 401, "title": "Unauthorized"}}
Googling around and using openstack token issue command showed me that usually, token are more like:
gAAAAABaCo1F1CIMVlsTBeuqYH8tm2qR29tbkmUL4vZuhCNPXJI39TQ2YzL6Twoj8fNcAyLe3WhCYW2O1YpbBF0G8mo4bt7Kf0IRsoDOoJ6uWa3RYyJ5SQNoB_5n8EnVXbKPxFYOZ_iFBnaVtL1_XDrGbwsrlDeyy8lZTDdLsqY52pUhFR-7Uow
which is not what I get with get_token.
What am I doing wrong?
Many thanks!
When you use the auth API directly, the token issued comes in the X-Subject-Token header.
Thus, to retrieve in your python example, you could access the response.headers dict like this:
token = r.headers['X-Subject-Token']
More info about authentication in the Keystone v3 docs
1. fetch authentication token as mentioned below:
r = requests.post(
OS_AUTH_URL+'/auth/tokens',
headers = HEADERS,
json = data,
verify = False
)
token = r.headers[X-Subject-Token]
2. Pass this token in header for further request:
{
'X-Auth-Token': token
}

Categories