บทแนะนำนี้จะอธิบายขั้นตอนที่จำเป็นในการเข้าถึงบัญชี Google Analytics, ค้นหา Analytics API, จัดการการตอบกลับของ API และแสดงผลลัพธ์ บทแนะนำนี้ใช้ Core Reporting API v3.0, Management API v3.0 และ OAuth2.0
ขั้นตอนที่ 1: เปิดใช้ Analytics API
หากต้องการเริ่มต้นใช้งาน Google Analytics API ก่อนอื่นคุณต้องใช้เครื่องมือการตั้งค่า ซึ่งจะแนะนำขั้นตอนการสร้างโปรเจ็กต์ในคอนโซล Google API เปิดใช้ API และสร้างข้อมูลเข้าสู่ระบบ
สร้างรหัสไคลเอ็นต์
- เปิดหน้าบัญชีบริการ เมื่อได้รับข้อความเตือน ให้เลือกโปรเจ็กต์
- คลิก สร้างบัญชีบริการ จากนั้นป้อนชื่อและคำอธิบายของบัญชีบริการ คุณจะใช้รหัสเริ่มต้นของบัญชีบริการ หรือเลือกรหัสอื่นที่ไม่ซ้ำกันก็ได้ เมื่อเสร็จแล้วให้คลิกสร้าง
- คุณข้ามส่วนสิทธิ์ของบัญชีบริการ (ไม่บังคับ) ที่ตามมาได้ คลิกต่อไป
- ในหน้าจอให้สิทธิ์ผู้ใช้เข้าถึงบัญชีบริการนี้ ให้เลื่อนลงไปที่ส่วนสร้างคีย์ คลิก สร้างคีย์
- เลือกรูปแบบของคีย์ในแผงด้านข้างที่ปรากฏขึ้น ขอแนะนำให้เลือก JSON
- คลิกสร้าง ระบบจะสร้างคู่คีย์สาธารณะ/ส่วนตัวใหม่และดาวน์โหลดลงในเครื่องของคุณ ซึ่งจะเป็นสำเนาเพียงรายการเดียวของคีย์นี้ ดูข้อมูลเกี่ยวกับวิธีจัดเก็บคีย์อย่างปลอดภัยที่การจัดการคีย์ของบัญชีบริการ
- คลิกปิดในกล่องโต้ตอบคีย์ส่วนตัวที่บันทึกไว้ในคอมพิวเตอร์ จากนั้นคลิกเสร็จเพื่อกลับไปที่ตารางของบัญชีบริการ
เพิ่มบัญชีบริการลงในบัญชี Google Analytics
บัญชีบริการที่สร้างใหม่จะมีอีเมล <projectId>-<uniqueId>@developer.gserviceaccount.com
ให้ใช้อีเมลนี้เพื่อเพิ่มผู้ใช้ในบัญชี Google Analytics ที่คุณต้องการเข้าถึงผ่าน API
สำหรับบทแนะนำนี้
ต้องใช้สิทธิ์อ่านและวิเคราะห์เท่านั้น
ขั้นตอนที่ 2: ติดตั้งไลบรารีของไคลเอ็นต์ Google
คุณจะใช้ตัวจัดการแพ็กเกจหรือดาวน์โหลดและติดตั้งไลบรารีของไคลเอ็นต์ Python ด้วยตนเองก็ได้โดยทำดังนี้
pip
ใช้ pip ซึ่งเป็นเครื่องมือแนะนำสำหรับการติดตั้งแพ็กเกจ Python ดังนี้
sudo pip install --upgrade google-api-python-client
เครื่องมือตั้งค่า
ใช้เครื่องมือ easy_install ที่มีอยู่ในแพ็กเกจ setuptools ดังนี้
sudo easy_install --upgrade google-api-python-client
การติดตั้งด้วยตนเอง
ดาวน์โหลดไลบรารีของไคลเอ็นต์สำหรับ Python ล่าสุด คลายการแพคข้อมูลโค้ดแล้วเรียกใช้
sudo python setup.py install
คุณอาจต้องเรียกใช้คำสั่งด้วยสิทธิ์ผู้ใช้ระดับสูง (sudo
) เพื่อติดตั้งใน Python ของระบบ
ขั้นตอนที่ 3: ตั้งค่าตัวอย่าง
คุณจะต้องสร้างไฟล์เดียวที่ชื่อ HelloAnalytics.py
ซึ่งจะมีโค้ดตัวอย่างที่ระบุ
- คัดลอกหรือ
ดาวน์โหลดซอร์สโค้ดต่อไปนี้ไปยัง
HelloAnalytics.py
- ย้าย
client_secrets.json
ที่ดาวน์โหลดไว้ก่อนหน้านี้ภายในไดเรกทอรีเดียวกันกับโค้ดตัวอย่าง - แทนที่ค่าของ
key_file_location
ด้วยค่าที่เหมาะสมจาก Developer Console
"""A simple example of how to access the Google Analytics API.""" from apiclient.discovery import build from oauth2client.service_account import ServiceAccountCredentials def get_service(api_name, api_version, scopes, key_file_location): """Get a service that communicates to a Google API. Args: api_name: The name of the api to connect to. api_version: The api version to connect to. scopes: A list auth scopes to authorize for the application. key_file_location: The path to a valid service account JSON key file. Returns: A service that is connected to the specified API. """ credentials = ServiceAccountCredentials.from_json_keyfile_name( key_file_location, scopes=scopes) # Build the service object. service = build(api_name, api_version, credentials=credentials) return service def get_first_profile_id(service): # Use the Analytics service object to get the first profile id. # Get a list of all Google Analytics accounts for this user accounts = service.management().accounts().list().execute() if accounts.get('items'): # Get the first Google Analytics account. account = accounts.get('items')[0].get('id') # Get a list of all the properties for the first account. properties = service.management().webproperties().list( accountId=account).execute() if properties.get('items'): # Get the first property id. property = properties.get('items')[0].get('id') # Get a list of all views (profiles) for the first property. profiles = service.management().profiles().list( accountId=account, webPropertyId=property).execute() if profiles.get('items'): # return the first view (profile) id. return profiles.get('items')[0].get('id') return None def get_results(service, profile_id): # Use the Analytics Service Object to query the Core Reporting API # for the number of sessions within the past seven days. return service.data().ga().get( ids='ga:' + profile_id, start_date='7daysAgo', end_date='today', metrics='ga:sessions').execute() def print_results(results): # Print data nicely for the user. if results: print 'View (Profile):', results.get('profileInfo').get('profileName') print 'Total Sessions:', results.get('rows')[0][0] else: print 'No results found' def main(): # Define the auth scopes to request. scope = 'https://www.googleapis.com/auth/analytics.readonly' key_file_location = '<REPLACE_WITH_JSON_FILE>' # Authenticate and construct service. service = get_service( api_name='analytics', api_version='v3', scopes=[scope], key_file_location=key_file_location) profile_id = get_first_profile_id(service) print_results(get_results(service, profile_id)) if __name__ == '__main__': main()
ขั้นตอนที่ 4: เรียกใช้ตัวอย่าง
หลังจากเปิดใช้ Analytics API แล้ว ให้ติดตั้งไลบรารีของไคลเอ็นต์ Google APIs สำหรับ Python และตั้งค่าซอร์สโค้ดตัวอย่างที่พร้อมเรียกใช้
เรียกใช้ตัวอย่างโดยใช้:
python HelloAnalytics.py
เมื่อทําตามขั้นตอนเหล่านี้เสร็จแล้ว ตัวอย่างจะแสดงชื่อข้อมูลพร็อพเพอร์ตี้ (โปรไฟล์) แรกของ Google Analytics ของผู้ใช้ที่ได้รับอนุญาตและจํานวนเซสชันในช่วง 7 วันที่ผ่านมา
ด้วยออบเจ็กต์บริการ Analytics ที่ได้รับอนุญาต ตอนนี้คุณจะเรียกใช้ตัวอย่างโค้ดที่อยู่ใน เอกสารอ้างอิงของ Management API ได้แล้ว ตัวอย่างเช่น คุณอาจลองเปลี่ยนโค้ดเพื่อใช้เมธอด accountSummaries.list
การแก้ปัญหา
AttributeError: ออบเจ็กต์ "Module_six_moves_urllib_parse" ไม่มีแอตทริบิวต์ "urlparse"
ข้อผิดพลาดนี้อาจเกิดขึ้นใน Mac OSX ที่มีการโหลดการติดตั้งเริ่มต้นของโมดูล "6" (ทรัพยากร Dependency ของไลบรารีนี้) โหลดก่อน PIP ที่ติดตั้ง หากต้องการแก้ไขปัญหา ให้เพิ่มตำแหน่งการติดตั้งของ PIP ลงในตัวแปรสภาพแวดล้อมระบบ PYTHONPATH
โดยทำดังนี้
-
ระบุตำแหน่งการติดตั้งของ PIP ด้วยคำสั่งต่อไปนี้
pip show six | grep "Location:" | cut -d " " -f2
-
เพิ่มบรรทัดต่อไปนี้ลงในไฟล์
~/.bashrc
โดยแทนที่<pip_install_path>
ด้วยค่าที่กำหนดข้างต้นexport PYTHONPATH=$PYTHONPATH:<pip_install_path>
-
โหลดไฟล์
~/.bashrc
ซ้ำในหน้าต่างเทอร์มินัลที่เปิดอยู่โดยใช้คำสั่งต่อไปนี้source ~/.bashrc