Google API 教程学习笔记

什么是Google API?

Google API是Google提供的接口,允许开发人员利用其庞大的数据集和服务来创建各种应用程序。

如何获取Google API密钥?

要使用Google API,您需要一个API密钥。 您可以通过以下步骤获取API密钥:

  1. 登录 Google Cloud Console
  2. 在左上角选择项目或创建新项目
  3. 在导航菜单中选择“API和服务”>“凭据”
  4. 点击“创建凭据”>“API密钥”

Google Maps API

Google Maps API是一个强大的工具,可为您的应用程序提供地图和位置信息。 以下是如何使用Google Maps API的简单示例:

htmlCopy Code
<!DOCTYPE html> <html> <head> <title>Google Map Example</title> <script src="https://maps.googleapis.com/maps/api/js?key=[YOUR_API_KEY]"></script> <script> function initMap() { var location = {lat: 37.7749, lng: -122.4194}; var map = new google.maps.Map(document.getElementById('map'), { zoom: 12, center: location }); var marker = new google.maps.Marker({ position: location, map: map }); } </script> </head> <body onload="initMap()"> <div id="map" style="height: 400px; width: 100%;"></div> </body> </html>

在上面的代码中,您需要用您自己获得的API密钥替换掉[YOUR_API_KEY]。该代码将创建一个地图,并在其上添加一个标记,该标记位于旧金山市中心。

Google Calendar API

Google Calendar API是一个可让您读取、创建和修改Google日历事件的API。以下是如何使用Google Calendar API的简单示例:

pythonCopy Code
import datetime from google.oauth2.credentials import Credentials from googleapiclient.discovery import build creds = Credentials.from_authorized_user_info(info) service = build('calendar', 'v3', credentials=creds) event = { 'summary': '测试事件', 'start': { 'dateTime': '2023-06-03T09:00:00', 'timeZone': 'America/Los_Angeles', }, 'end': { 'dateTime': '2023-06-03T17:00:00', 'timeZone': 'America/Los_Angeles', }, 'attendees': [ {'email': 'test1@gmail.com'}, {'email': 'test2@gmail.com'}, ], } event = service.events().insert(calendarId='primary', body=event).execute() print(f'Event created: {event.get("htmlLink")}')

在上面的代码中,您需要先准备好Google API的认证信息,然后用代码创建一个日历事件并添加到您的Google Calendar。