使用 API

本文件說明使用 Google Civic Information API 時,您需要瞭解的相關資訊。您可以參閱這份公民資訊 API 常見問題,瞭解 API 的相關基本資訊,以及使用者論壇的常見問題。此外,您也可以參考下列範例,瞭解如何在選舉期間查詢選民資訊

讓 Google 識別您的應用程式

每當應用程式傳送要求給 Google Civic Information API 時,都必須在每個要求中加入 API 金鑰,以便識別自身。

取得並使用 API 金鑰

要取得 API 金鑰:

  1. 在 API 控制台中開啟「憑證」頁面。
  2. 此 API 支援兩種憑證。請建立適用於您專案的憑證:
    • OAuth 2.0:每當您的應用程式要求私人使用者資料時,必須同時傳送 OAuth 2.0 憑證。您的應用程式會先傳送用戶端 ID,並可能傳送用戶端密碼以獲取憑證。您可以為網路應用程式、服務帳戶或已安裝的應用程式產生 OAuth 2.0 憑證。

      注意:由於這個 API 沒有任何需要 OAuth 2.0 授權的方法,因此您可能只需要取得API 金鑰,如以下所述。不過,如果您的應用程式呼叫需要使用者授權的其他 API,則仍需要 OAuth 2.0 憑證。

      詳情請參閱 OAuth 2.0 說明文件

    • API 金鑰:沒有提供 OAuth 2.0 憑證的要求必須傳送 API 金鑰。金鑰可用來識別專案,並為您提供 API 存取權、配額和報表。

      API 支援數種類型的 API 金鑰限制。如果您還沒有所需的 API 金鑰,請依序點選「Create credentials」 >「API key」,在主控台中建立 API 金鑰。在您將金鑰使用在實際工作環境中之前,可以點選「Restrict key」(限制金鑰) 並選擇其中一項「Restrictions」(限制)以限制金鑰的使用。

為確保您 API 金鑰的安全,請遵循安全使用 API 金鑰的最佳做法

取得 API 金鑰後,您的應用程式可以將查詢參數 key=yourAPIKey 附加到所有的要求網址。

API 金鑰可以安全地嵌入網址中,不需任何編碼。

API 金鑰限制

根據預設,API 金鑰是不受限制的,如果任何人都能讀取這個金鑰 (例如放置在瀏覽器內),或是存取放置金鑰的裝置,就會造成安全性問題。建議您為這個 API 金鑰設定限制,以防止未經授權的使用行為。

如要新增限制,請在「建立的 API 金鑰」對話方塊中按一下「限制金鑰」。系統會顯示「API 金鑰」設定面板:

您選取的限制類型取決於應用程式需求:

  • 直接與 API 互動的網頁應用程式 (也就是未透過任何後端或中介軟體) 應新增 HTTP 參照網址限制。不過請注意,這類應用程式會公開自己的 API 金鑰,建議改用服務帳戶驗證方案。
  • 無法支援服務帳戶的後端應用程式 (例如,嵌入式裝置在用戶端程式庫中沒有支援的語言),應新增 IP 位址限制,以防範來自不同 IP 位址的用戶端使用。
  • Android 應用程式應新增 Android 應用程式限制,並新增套件名稱和 SHA-1 簽署憑證指紋。
  • iOS 應用程式應新增 iOS 應用程式限制,並加入任何 iOS 軟體包 ID,以限制對這些 iOS 軟體包的 API 呼叫。

如要進行測試,您可能不想設定任何限制。不過,建議您在將應用程式部署至正式環境後,為這個金鑰新增限制或將其刪除。

electionQuery 範例

以下是呼叫 electionQuery API 的範例 (使用 API 版本「v2」),用於取得有效選舉 ID 清單,然後使用 voterInfoQuery API 搭配選民註冊地址,取得所選選舉的相關資訊。

使用 electionQuery 取得有效的選舉 ID 清單:

  https://www.googleapis.com/civicinfo/v2/elections?key=<YOUR_API_KEY>
  

electionQuery 回應:

{
 "kind": "civicinfo#electionsqueryresponse",
 "elections": [
  {
   "id": "2000",
   "name": "VIP Test Election",
   "electionDay": "2013-06-06"
  },
  {
   "id": "2124",
   "name": "Rhode Island 2012 Primary Election",
   "electionDay": "2012-09-11"
  },
  {
   "id": "2126",
   "name": "Delaware 2012 Primary Election",
   "electionDay": "2012-09-11"
  }
 ]
}

使用 curl 執行 voterInfoQuery

使用 curl 傳送 voterInfoQuery 要求,針對 VIP 測試選舉 ID 2000 和位於 (測試) 地址 340 Main St, Venice, CA 90291 的選民。您可以參考 voterInfoQuery 回應

curl "https://www.googleapis.com/civicinfo/v2/voterinfo?key=<YOUR_API_KEY>&address=340%20Main%20St.%20Venice%20CA&electionId=2000"

使用適用於 JavaScript 的 Google API 用戶端程式庫執行 voterInfoQuery

本範例會發出與前一個 curl 範例相同的 voterInfoQuery,但會使用 JavaScript 用戶端程式庫voterInfoQuery 回應與 curl 範例回應相同。

<!doctype html>
<html>
  <head>
    <script>
      /**
       * Build and execute request to look up voter info for provided address.
       * @param {string} address Address for which to fetch voter info.
       * @param {function(Object)} callback Function which takes the
       *     response object as a parameter.
       */
       function lookup(address, callback) {
       /**
         * Election ID for which to fetch voter info.
         * @type {number}
         */
        var electionId = 2000;
 
        /**
         * Request object for given parameters.
         * @type {gapi.client.HttpRequest}
         */
        var req = gapi.client.request({
            'path' : '/civicinfo/v2/voterinfo',
            'params' : {'electionId' : electionId, 'address' : address}
        });
       req.execute(callback);
      }

      /**
       * Render results in the DOM.
       * @param {Object} response Response object returned by the API.
       * @param {Object} rawResponse Raw response from the API.
       */
      function renderResults(response, rawResponse) {
        var el = document.getElementById('results');
        if (!response || response.error) {
          el.appendChild(document.createTextNode(
              'Error while trying to fetch polling place'));
          return;
        }
        var normalizedAddress = response.normalizedInput.line1 + ' ' +
            response.normalizedInput.city + ', ' +
            response.normalizedInput.state + ' ' +
            response.normalizedInput.zip;
        if (response.pollingLocations.length > 0) {
          var pollingLocation = response.pollingLocations[0].address;
          var pollingAddress = pollingLocation.locationName + ', ' +
              pollingLocation.line1 + ' ' +
              pollingLocation.city + ', ' +
              pollingLocation.state + ' ' +
              pollingLocation.zip;
          var normEl = document.createElement('strong');
          normEl.appendChild(document.createTextNode(
              'Polling place for ' + normalizedAddress + ': '));
          el.appendChild(normEl);
          el.appendChild(document.createTextNode(pollingAddress));
        } else {
          el.appendChild(document.createTextNode(
              'Could not find polling place for ' + normalizedAddress));
        }
      }

      /**
       * Initialize the API client and make a request.
       */
      function load() {
        gapi.client.setApiKey('YOUR API KEY GOES HERE');
        lookup('1263 Pacific Ave. Kansas City KS', renderResults);
      }
    </script>
    <script src="https://apis.google.com/js/client.js?onload=load"></script>
  </head>
  <body>
    <div id="results"></div>
  </body>
</html>

voterInfoQuery 回應

{
  "kind": "civicinfo#voterinforesponse",
  "status": "success",
  "election": {
  "id": "2000",
  "name": "VIP Test Election",
  "electionDay": "2025-06-06",
  "ocdDivisionId": "ocd-division/country:us"
  },
  "normalizedInput": {
    "line1": "340 Main Street",
    "city": "Venice",
    "state": "CA",
    "zip": "90291"
  },
  "pollingLocations": [
    {
      "address": {
        "locationName": "WESTMINSTER AVENUE ELEMENTARY SCHOOL",
        "line1": "1010 ABBOT KINNEY BLVD",
        "city": "VENICE",
        "state": "CA",
        "zip": "90291"
      },
      "pollingHours": "",
      "latitude": 33.9919351,
      "longitude": -118.4722031,
      "startDate": "2024-03-05",
      "endDate": "2024-03-05",
      "sources": [
        {
          "name": "Voting Information Project",
          "official": true
        }
      ]
    },
    {
      "address": {
        "locationName": "POP UP VOTE CENTER 5",
        "line1": "12400 IMPERIAL HWY",
        "city": "NORWALK",
        "state": "CA",
        "zip": "90650"
      },
      "latitude": 33.915989,
      "longitude": -118.0677283,
      "sources": [
        {
          "name": "Voting Information Project",
          "official": true
        }
      ]
    }
  ],
  "dropOffLocations": [
    {
      "address": {
        "locationName": "FLEX VOTE CENTER 9",
        "line1": "12400 IMPERIAL HWY",
        "city": "NORWALK",
        "state": "CA",
        "zip": "90650"
      },
      "latitude": 33.915989,
      "longitude": -118.0677283,
      "sources": [
        {
          "name": "Voting Information Project",
          "official": true
        }
      ]
    },
  ],
  "contests": [
    {
      "type": "General",
      "ballotTitle": "UNITED STATES REPRESENTATIVE, 36th District",
      "district": {
        "name": "36TH US CONGRESSIONAL",
        "scope": "congressional"
      },
      "numberElected": "1",
      "numberVotingFor": "1",
      "ballotPlacement": "103",
      "sources": [
        {
          "name": "Voting Information Project",
          "official": true
        }
      ],
      "candidates": [
        {
          "name": "ARIANA HAKAMI",
          "party": "Party Preference: Republican"
        },
        {
          "name": "CLAIRE RAGGE ANDERSON",
          "party": "Party Preference: None"
        },
        {
          "name": "MELISSA TOOMIM",
          "party": "Party Preference: Republican"
        },
        {
          "name": "TED W. LIEU",
          "party": "Party Preference: Democratic"
        }
      ]
    },
    {
      "type": "ballot-measure",
      "ballotTitle": "LOS ANGELES CITY MUNICIPAL ELECTION - MEASURE HLA",
      "district": {
        "name": "CITY OF LOS ANGELES",
        "scope": "citywide"
      },
      "ballotPlacement": "116",
      "referendumTitle": "LOS ANGELES CITY MUNICIPAL ELECTION - MEASURE HLA",
      "referendumText": "CITY MOBILITY PLAN STREET IMPROVEMENT MEASURES. INITIATIVE ORDINANCE HLA. Shall an ordinance providing that when the City of Los Angeles makes a qualifying improvement to a City-owned street (e.g., a paving project), the City must also install certain street enhancements described in the City's Mobility Plan network of pedestrian, bicycle, transit, and vehicle routes; and requiring the City to provide publicly accessible information regarding street improvements; be adopted?",
      "referendumPassageThreshold": "MAJORITY OF VOTES CAST",
      "referendumBallotResponses": [
        "YES",
        "NO"
      ],
      "sources": [
        {
          "name": "Voting Information Project",
          "official": true
        }
      ]
    },
    {
      "type": "General",
      "ballotTitle": "DISTRICT ATTORNEY",
      "district": {
        "name": "LOS ANGELES COUNTY",
        "scope": "countywide"
      },
      "numberElected": "1",
      "numberVotingFor": "1",
      "ballotPlacement": "129",
      "sources": [
        {
          "name": "Voting Information Project",
          "official": true
        }
      ],
      "candidates": [
        {
          "name": "GEORGE GASCÓN"
        },
        {
          "name": "JONATHAN HATAMI"
        },
        {
          "name": "NATHAN HOCHMAN"
        },
        {
          "name": "DEBRA ARCHULETA"
        },
        {
          "name": "JEFF CHEMERINSKY"
        },
        {
          "name": "ERIC SIDDALL"
        },
        {
          "name": "MARIA RAMIREZ"
        },
        {
          "name": "DAN KAPELOVITZ"
        },
        {
          "name": "LLOYD \"BOBCAT\" MASSON"
        },
        {
          "name": "JOHN MCKINNEY"
        },
        {
          "name": "CRAIG J. MITCHELL"
        },
        {
          "name": "DAVID S. MILTON"
        }
      ]
    }
  ],
  "state": [
    {
      "name": "California",
      "electionAdministrationBody": {
        "name": "Secretary of State",
        "electionInfoUrl": "https://www.sos.ca.gov/elections/",
        "electionRegistrationUrl": "https://registertovote.ca.gov/?t=s",
        "electionRegistrationConfirmationUrl": "https://voterstatus.sos.ca.gov",
        "absenteeVotingInfoUrl": "https://elections.cdn.sos.ca.gov/vote-by-mail/replacement-application.pdf",
        "votingLocationFinderUrl": "https://voterstatus.sos.ca.gov",
        "ballotInfoUrl": "https://www.sos.ca.gov/elections/ballot-status/wheres-my-ballot/",
        "correspondenceAddress": {
          "line1": "1500 11th Street, 5th Floor",
          "city": "Sacramento",
          "state": "California",
          "zip": "95814"
        }
      },
      "local_jurisdiction": {
        "name": "Los Angeles",
        "electionAdministrationBody": {
          "name": "Registrar-Recorder/County Clerk",
          "electionInfoUrl": "http://www.lavote.gov/",
          "electionRegistrationUrl": "http://registertovote.ca.gov/",
          "electionRegistrationConfirmationUrl": "https://lavote.gov/vrstatus/",
          "absenteeVotingInfoUrl": "",
          "ballotInfoUrl": "http://www.lavote.gov/Locator",
          "physicalAddress": {
            "locationName": "Registrar-Recorder/County Clerk",
            "line1": "12400 Imperial Highway",
            "city": "Norwalk",
            "state": "CA",
            "zip": "90650"
          }
        },
        "sources": [
          {
            "name": "Voting Information Project",
            "official": true
          }
        ]
      }
    }
  ]
}