Создавайте новые контакты через API контактов Google или API людей - PullRequest
0 голосов
/ 01 декабря 2019

Можно ли создавать контакты Google с помощью API контактов Google или API людей?

У меня возникают проблемы при создании новых контактов с помощью API Google.

Я ищу несколько днейи нашел следующую информацию:

1 - похоже, что пакет API людей приходит на смену API контактов Google

https://gsuite -developers.googleblog.com / 2017/07 / google-people-api-now-support-updates.html

2 - Многие люди не могут создавать новые контакты с помощью Python 3+ с использованием пакетов gdata и atom.

3 - людиAPI отображается в соответствии с рекомендациями Gsuite

https://support.google.com/a/answer/6103110?hl=pt-BR

Я хотел бы знать, создает ли кто-нибудь новые контакты с помощью этих API Google.

Требуется ли электронная почта ag Suite?

Как получить токен доступа?

Я выполнил все настройки на облачной платформе Google (включил API и auth2), у меня есть файл json, секретный ключ и идентификатор клиента

edit:

Мне удается перечислить мои 50 контактов сэтот код, мне нужно изменить блоки для создания новых контактов

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/contacts']

def main():
    """Shows basic usage of the People API.
    Prints the name of the first 10 connections.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('people', 'v1', credentials=creds)

    # Call the People API
    print('List 50 connection names')
    results = service.people().connections().list(
        resourceName='people/me',
        pageSize=50,
        personFields='names,emailAddresses').execute()
    connections = results.get('connections', [])

    for person in connections:
        names = person.get('names', [])
        if names:
            name = names[0].get('displayName')
            print(name)

if __name__ == '__main__':
    main()

1 Ответ

1 голос
/ 02 декабря 2019

Поскольку у вас уже есть авторизация, работающая над списком контактов, вы должны иметь возможность сделать что-то вроде этого для создания:

newContact = { "names": [{ "givenName": "John", "familyName": "Doe" }] }
result = service.people().createContact(body=newContact).execute()

Полное определение того, что может быть в теле / ​​человеке: здесь .

...