如何使用People API创建新联系人

时间:2019-12-02 18:59:25

标签: python post google-cloud-platform google-api google-people-api

我正在尝试使用python和people API在公司中创建多个联系人。

我已经对其进行了研究,发现我需要使用人员API通过API编辑联系人,但是我找不到如何实现此目的的好例子。

我正在使用以下命令来列出我的联系人的简单列表:

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
    import urllib3

    # 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 10 connection names')
        results = service.people().connections().list(
            resourceName='people/me',
            pageSize=10,
            personFields='names,phoneNumbers').execute()
        connections = results.get('connections', [])

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

    if __name__ == '__main__':
        main()

输出:

List 10 connection names
Eeverton None
Evetton None
Paulinha None
Wayne +5521992*****
Joao Pedro +55219643*****
Mae +552199*****
Maae +552199*****
Advogado Gb +5521964*****

完美的工作。

但是我需要创建新的联系人。

  1. 我更改了范围

  2. 我已验证了oauth2

  3. 我已经正确存储了所有文件和密钥(token.picke和凭据.json)

我应该如何创建新的联系人?功能还是POST?

您能否提供一个用于创建联系人的简单代码示例?

https://developers.google.com/people/api/rest/v1/people/createContact

2 个答案:

答案 0 :(得分:1)

我建议您尝试这段代码:

from __future__ import print_function
import httplib2
import os

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/people.googleapis.com-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/contacts'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'People API Python Quickstart'


def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser('./')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'people.googleapis.com-python-quickstart.json')

    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('people', 'v1', http=http,
    discoveryServiceUrl='https://people.googleapis.com/$discovery/rest')
service.people().createContact(parent='people/me', body={
        "names": [
            {
                "givenName": "Samkit"
            }
        ],
        "phoneNumbers": [
            {
                'value': "8600086024"
            }
        ],
        "emailAddresses": [
            {
                'value': 'samkit5495@gmail.com'
            }
        ]
    }).execute()

我希望这会有所帮助。

答案 1 :(得分:0)

适用于:

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

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
    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)

    # CREATING CONTACTSSSSSSSS
    service.people().createContact( body={
        "names": [
            {
                "givenName": "Samkit"
            }
        ],
        "phoneNumbers": [
            {
                'value': "8600086024"
            }
        ],
        "emailAddresses": [
            {
                'value': 'samkit5495@gmail.com'
            }
        ]
    }).execute()



if __name__ == '__main__':
    main()