שימוש ב-API

במסמך הזה מוסבר מה צריך לדעת כדי להשתמש ב-Google Civic Information API. אפשר לעיין בשאלות הנפוצות בנושא Civic Info API, שמכילה מידע בסיסי על ה-API וגם שאלות נפוצות מפורום המשתמשים שלנו. בנוסף, בהמשך מפורטות דוגמאות לחיפוש פרטי בוחרים במהלך בחירות.

זיהוי האפליקציה ב-Google

האפליקציה צריכה לזהות את עצמה בכל פעם שהיא שולחת בקשה ל-Google Civic Information API, על ידי צירוף מפתח API לכל בקשה.

קבלה של מפתח API ושימוש בו

כדי לקבל מפתח API:

  1. פותחים את דף פרטי הכניסה במסוף ה-API.
  2. ה-API הזה תומך בשני סוגים של פרטי כניסה. יוצרים את פרטי הכניסה המתאימים לפרויקט:
    • OAuth 2.0: בכל פעם שהאפליקציה שלכם מבקשת נתונים פרטיים של משתמשים, היא צריכה לשלוח אסימון OAuth 2.0 יחד עם הבקשה. האפליקציה שולחת קודם מזהה לקוח, ואולי גם סוד לקוח, כדי לקבל אסימון. אפשר ליצור פרטי כניסה של OAuth 2.0 לאפליקציות אינטרנט, לחשבונות שירות או לאפליקציות מותקנות.

      הערה: מאחר של-API הזה אין שיטות שדורשות הרשאה של OAuth 2.0, יכול להיות שתצטרכו לקבל רק מפתחות API, שמתוארים בהמשך. עם זאת, אם האפליקציה שלכם קוראת לממשקי API אחרים שדורשים הרשאה מהמשתמש, עדיין תצטרכו פרטי כניסה ל-OAuth 2.0.

      למידע נוסף, ראו מסמכי התיעוד של OAuth 2.0.

    • מפתחות API: בקשה שלא מספקת אסימון OAuth 2.0 חייבת לשלוח מפתח API. המפתח מזהה את הפרויקט ומספק גישה ל-API, מכסות ודוחות.

      ה-API תומך במספר סוגים של הגבלות על מפתחות API. אם מפתח ה-API הנדרש עדיין לא קיים, צריך ליצור מפתח API במסוף. לשם כך, לוחצים על Create credentials  > API key. כדי להגביל את המפתח לפני השימוש בו בסביבת הייצור, לוחצים על Restrict key ובוחרים באחת מהRestrictions.

כדי לשמור על האבטחה של מפתחות ה-API, כדאי לפעול לפי השיטות המומלצות לשימוש מאובטח במפתחות API.

אחרי שתקבלו מפתח API, תוכלו להוסיף את פרמטר השאילתה key=yourAPIKey לכל כתובות ה-URL של הבקשות.

מפתח ה-API בטוח להטמעה בכתובות URL, ואין צורך בקידוד שלו.

הגבלות על מפתחות API

כברירת מחדל, אין הגבלות על מפתח ה-API. מצב כזה לא מאובטח אם כל אחד יכול לקרוא את המפתח הזה (למשל, אם הוא ממוקם בדפדפן) או לגשת למכשיר שבו המפתח ממוקם. מומלץ להחיל הגבלה על מפתח ה-API הזה כדי למנוע שימוש לא מורשה.

כדי להוסיף הגבלה, לוחצים על Restrict key בתיבת הדו-שיח API key created. תיפתח חלונית ההגדרה של מפתח ה-API:

סוג ההגבלה שתבחרו יהיה תלוי בצרכים של האפליקציה:

  • אפליקציות אינטרנט שמקיימות אינטראקציה ישירה עם ה-API (כלומר, לא דרך קצה עורפי או תוכנה לעיבוד נתונים ביניים) צריכות להוסיף הגבלה על גורמים מפנים מסוג HTTP. עם זאת, חשוב לזכור שאפליקציות כאלה חושפות את מפתח ה-API שלהן באופן ציבורי. מומלץ להשתמש במקום זאת בסכימת אימות של חשבון שירות.
  • באפליקציות לקצה העורפי שלא ניתן לתמוך בהן בחשבונות שירות בדרכים אחרות (למשל, במכשירים מוטמעים שאין להם שפה נתמכת בספריית הלקוח), צריך להוסיף הגבלה על כתובות IP כדי להגן מפני שימוש מלקוחות בכתובות IP שונות.
  • באפליקציות ל-Android צריך להוסיף הגבלה של אפליקציות ל-Android ולהוסיף את שם החבילה ואת טביעת האצבע של אישור החתימה SHA-1.
  • באפליקציות ל-iOS צריך להוסיף הגבלה מסוג אפליקציות ל-iOS ולהוסיף את מזהי החבילות של iOS כדי להגביל את הקריאות ל-API לחבילות האלה של iOS.

לצורך בדיקה, יכול להיות שלא תרצו להחיל הגבלה בכלל. עם זאת, מומלץ להוסיף הגבלה למפתח הזה או למחוק אותו אחרי הפריסה של האפליקציה בסביבת הייצור.

דוגמה ל-electionQuery

לפניכם דוגמה (בגרסת API v2) לקריאה ל-API electionQuery כדי לקבל רשימה של מזהי בחירות תקפים, ולאחר מכן ל-API voterInfoQuery עם הכתובת הרשומה של הבוחר כדי לקבל מידע על בחירה שנבחרה.

משתמשים ב-electionQuery כדי לקבל רשימה של מזהי בחירות תקפים:

  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"
  }
 ]
}

קריאה של voterInfoQuery באמצעות curl

משתמשים ב-curl כדי לשלוח בקשה מסוג voterInfoQuery למזהה הבחירות לבדיקה של VIP‏ 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"

קריאה של voterInfoQuery באמצעות ספריית הלקוח של Google API ל-JavaScript

בדוגמה הזו מונפקת אותה שאילתה voterInfoQuery כמו בדוגמה הקודמת של curl, אבל היא משתמשת בספריית הלקוח של 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
          }
        ]
      }
    }
  ]
}