Tài liệu này mô tả những điều bạn cần biết để sử dụng API Thông tin công dân của Google. Bạn có thể xem Câu hỏi thường gặp về API Thông tin công cộng này. Trang này có một số thông tin cơ bản về API cũng như các câu hỏi thường gặp trên diễn đàn người dùng của chúng tôi. Ngoài ra, bạn có thể xem các ví dụ bên dưới để tra cứu thông tin cử tri trong một cuộc bầu cử.
Xác định ứng dụng của bạn với Google
Ứng dụng của bạn cần tự xác định mỗi khi gửi yêu cầu đến API Thông tin công dân của Google, bằng cách đưa khoá API vào mỗi yêu cầu.
Lấy và sử dụng khoá API
Cách lấy khoá API:
- Mở trang Thông tin xác thực trong API Console.
-
API này hỗ trợ hai loại thông tin xác thực.
Tạo thông tin xác thực phù hợp với dự án của bạn:
-
OAuth 2.0: Bất cứ khi nào ứng dụng của bạn yêu cầu dữ liệu riêng tư của người dùng, ứng dụng đó phải gửi mã thông báo OAuth 2.0 cùng với yêu cầu. Trước tiên, ứng dụng của bạn sẽ gửi mã ứng dụng khách và có thể là khoá bí mật của ứng dụng khách để lấy mã thông báo. Bạn có thể tạo thông tin xác thực OAuth 2.0 cho ứng dụng web, tài khoản dịch vụ hoặc ứng dụng đã cài đặt.
Lưu ý: Vì API này không có phương thức nào yêu cầu uỷ quyền OAuth 2.0, nên có thể bạn chỉ cần lấy khoá API được mô tả bên dưới. Tuy nhiên, nếu ứng dụng của bạn gọi các API khác yêu cầu người dùng uỷ quyền, thì bạn vẫn cần thông tin xác thực OAuth 2.0.
Để biết thêm thông tin, hãy xem tài liệu về OAuth 2.0.
-
Khoá API: Một yêu cầu không cung cấp mã thông báo OAuth 2.0 phải gửi một khoá API. Khoá này xác định dự án của bạn và cung cấp quyền truy cập API, hạn mức và báo cáo.
API này hỗ trợ một số loại hạn chế đối với khoá API. Nếu khoá API mà bạn cần chưa tồn tại, hãy tạo khoá API trong Console bằng cách nhấp vào Tạo thông tin xác thực > Khoá API. Bạn có thể hạn chế khoá trước khi sử dụng khoá đó trong phiên bản chính thức bằng cách nhấp vào Hạn chế khoá rồi chọn một trong các Hạn chế.
-
Để bảo mật khoá API, hãy làm theo các phương pháp hay nhất để sử dụng khoá API một cách an toàn.
Sau khi bạn có khoá API, ứng dụng của bạn có thể thêm tham số truy vấn key=yourAPIKey
vào tất cả URL yêu cầu.
Khoá API an toàn để nhúng vào URL; không cần mã hoá.
Các quy tắc hạn chế đối với khoá API
Theo mặc định, khoá API của bạn không bị hạn chế. Điều này sẽ không an toàn nếu bất kỳ ai cũng có thể đọc khoá này (ví dụ: nếu khoá được đặt trong trình duyệt) hoặc truy cập vào thiết bị chứa khoá. Bạn nên đặt hạn chế đối với khoá API này để ngăn chặn việc sử dụng trái phép.
Để thêm quy tắc hạn chế, hãy nhấp vào Restrict key (Hạn chế khoá) trong hộp thoại API key created (Khoá API đã tạo). Bảng điều khiển cấu hình Khoá API sẽ xuất hiện:

Loại hạn chế mà bạn chọn sẽ phụ thuộc vào nhu cầu của ứng dụng:
- Các ứng dụng web tương tác trực tiếp với API (tức là không thông qua bất kỳ phần phụ trợ hoặc phần mềm trung gian nào) phải thêm quy tắc hạn chế Trình giới thiệu HTTP. Tuy nhiên, xin lưu ý rằng các ứng dụng như vậy sẽ hiển thị khoá API công khai; tốt hơn hết bạn nên sử dụng lược đồ xác thực tài khoản dịch vụ.
- Các ứng dụng phụ trợ không thể hỗ trợ tài khoản dịch vụ (ví dụ: các thiết bị nhúng không có ngôn ngữ được hỗ trợ trong thư viện ứng dụng) nên thêm quy tắc hạn chế địa chỉ IP để bảo vệ khỏi việc sử dụng của các ứng dụng tại các địa chỉ IP khác nhau.
- Ứng dụng Android phải thêm một quy tắc hạn chế Ứng dụng Android và thêm tên gói cũng như vân tay số SHA-1 của chứng chỉ ký.
- Ứng dụng iOS phải thêm một quy tắc hạn chế ứng dụng iOS và thêm mọi giá trị nhận dạng gói iOS để hạn chế các lệnh gọi API đến các gói iOS này.
Để thử nghiệm, bạn có thể không muốn đặt bất kỳ hạn chế nào. Tuy nhiên, bạn nên thêm hạn chế vào khoá này hoặc xoá khoá này sau khi triển khai ứng dụng của mình sang môi trường phát hành công khai.
Ví dụ về electionQuery
Sau đây là ví dụ (sử dụng API phiên bản "v2") về cách gọi API electionQuery để lấy danh sách mã cử tri hợp lệ, sau đó sử dụng API voterInfoQuery với địa chỉ đã đăng ký của cử tri để lấy thông tin về một cuộc bầu cử đã chọn.
Sử dụng electionQuery để lấy danh sách mã cuộc bầu cử hợp lệ:
https://www.googleapis.com/civicinfo/v2/elections?key=<YOUR_API_KEY>
Phản hồi 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 sử dụng curl
Sử dụng curl
để gửi yêu cầu voterInfoQuery cho mã bầu cử thử nghiệm VIP 2000 và người bầu cử tại địa chỉ (thử nghiệm) 340 Main St, Venice, CA 90291.
Bạn có thể tham khảo phản hồi voterInfoQuery.
curl "https://www.googleapis.com/civicinfo/v2/voterinfo?key=<YOUR_API_KEY>&address=340%20Main%20St.%20Venice%20CA&electionId=2000"
voterInfoQuery sử dụng Thư viện ứng dụng API của Google cho JavaScript
Ví dụ này đưa ra cùng một voterInfoQuery như ví dụ curl trước, nhưng sử dụng thư viện ứng dụng JavaScript. Phản hồi voterInfoQuery giống với phản hồi mẫu 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>
Phản hồi 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 } ] } } ] }