Thư viện ứng dụng

Trang này cung cấp các ví dụ về thư viện ứng dụng để truy cập vào Google Health API.

API Google Health được xây dựng trên HTTP và JSON, do đó, mọi ứng dụng HTTP tiêu chuẩn đều có thể gửi yêu cầu tới API này và phân tích cú pháp các phản hồi.

Tuy nhiên, thay vì tạo yêu cầu HTTP và phân tích cú pháp phản hồi theo cách thủ công, bạn có thể muốn sử dụng các ví dụ về thư viện ứng dụng và nội dung tải xuống được giới thiệu tại đây.

Java

  1. Thêm Thư viện ứng dụng API của Google:
    • Đưa thư viện vào dự án của bạn (bằng Maven hoặc Gradle).
  2. Triển khai quy trình OAuth 2.0:
    • Sử dụng google-auth-library-java để xử lý quy trình OAuth.
  3. Đưa ra yêu cầu API:
    • Sử dụng ứng dụng khách đã khởi tạo để gửi yêu cầu đến Google Health API.
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.health.v1.Health; // Assuming a generated Google Health API client
import com.google.api.services.health.v1.model.DataResponse; // Example: Response model
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Scanner;

public class GoogleHealthApiExample {

    private static final String CLIENT_SECRETS_PATH = "path/to/your/client_secret.json";
    private static final String TOKENS_DIRECTORY_PATH = "tokens";
    private static final String API_KEY = "YOUR_API_KEY";
    private static final List<String> SCOPES = Collections.singletonList("https://www.googleapis.com/auth/health");
    private static final String APPLICATION_NAME = "Google Health API Example";
    private static final String DISCOVERY_URL = "https://health.googleapis.com/$discovery/rest"; // Adjust if needed

    private static final JsonFactory JSON_FACTORY = new GsonFactory();
    private static FileDataStoreFactory dataStoreFactory;
    private static HttpTransport httpTransport;

    static {
        try {
            httpTransport = GoogleNetHttpTransport.newTrustedTransport();
            dataStoreFactory = new FileDataStoreFactory(new File(TOKENS_DIRECTORY_PATH));
        } catch (GeneralSecurityException | IOException e) {
            throw new RuntimeException("Error initializing HttpTransport or DataStoreFactory", e);
        }
    }


    public static void main(String[] args) {
        try {
             Health healthService = createHealthService();
             fetchHealthData(healthService);
        } catch (Exception e) {
            System.err.println("Error during execution: " + e.getMessage());
             e.printStackTrace();
        }
    }

    private static Health createHealthService() throws IOException {
        Credential credential = getCredentials();
        return new Health.Builder(httpTransport, JSON_FACTORY, credential)
                .setApplicationName(APPLICATION_NAME)
                .setGoogleClientRequestInitializer(request -> {
                    request.set("key", API_KEY);
                })
                .setRootUrl(DISCOVERY_URL)
                .build();
    }

    private static Credential getCredentials() throws IOException {
        // Load client secrets
        InputStream in = Objects.requireNonNull(GoogleHealthApiExample.class.getClassLoader().getResourceAsStream(CLIENT_SECRETS_PATH),
                "client_secret.json not found");
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

        // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                httpTransport, JSON_FACTORY, clientSecrets, SCOPES)
                .setDataStoreFactory(dataStoreFactory)
                .setAccessType("offline") // Allows for refresh tokens
                .build();

        Credential credential = flow.loadCredential("user"); // "user" is a key for storing/loading credentials.
        if (credential == null || !credential.getAccessToken() != null && credential.getExpiresInSeconds() <= 60) {
            // Prompt user to authorize and get new credentials
            System.out.println("Please open the following URL in your browser and authorize the app:");
            System.out.println(flow.newAuthorizationUrl().setRedirectUri("urn:ietf:wg:oauth:2.0:oob").build());
            System.out.print("Enter the authorization code: ");
            String code = new Scanner(System.in).nextLine();
            credential = flow.createAndStoreCredential(
                    flow.newTokenRequest(code).setRedirectUri("urn:ietf:wg:oauth:2.0:oob").execute(), "user"
            );
        }
        return credential;
    }

    private static void fetchHealthData(Health client) throws IOException {
        try {
            // Example: Replace with actual API method calls
            Health.Users.Data.List request = client.users().data().list();
            DataResponse response = request.execute();
            System.out.println("Health data: " + response);
        } catch (Exception e) {
            System.err.println("Error fetching health data: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
  // Process the response
  if (response.statusCode() == 200) {
      System.out.println("API Response: " + response.body());
  } else {
      System.err.println("Error: " + response.statusCode() + " " + response.body());
}
  • Nhập thư viện:
    • com.google.api.client.*: Thư viện cốt lõi cho ứng dụng Google API.
    • com.google.api.services.health.*: Các lớp được tạo cho Google Health API. (Bạn sẽ cần tạo khoá này dựa trên tài liệu khám phá của API).
  • Cấu hình:
    • CLIENT_SECRETS_PATH: Đường dẫn đến tệp client_secret.json.
    • TOKENS_DIRECTORY_PATH: Đường dẫn lưu trữ mã thông báo.
    • API_KEY: Khoá API của bạn.
    • SCOPES: Các quyền bắt buộc.
    • DISCOVERY_URL: URL để lấy định nghĩa API.
  • main Phương thức:
    • Khởi chạy ứng dụng Google Health API và gọi fetchHealthData.
  • createHealthService():
    • Tạo một phiên bản của ứng ứng dụng Google Health API, thiết lập thông tin xác thực, tên ứng dụng và khoá API.
  • getCredentials():
    • Tải khoá bí mật của ứng dụng khách từ tệp.
    • Tạo GoogleAuthorizationCodeFlow.
    • Cố gắng tải thông tin đăng nhập đã lưu trữ.
    • Nếu không tìm thấy thông tin đăng nhập hoặc thông tin đăng nhập đã hết hạn, hãy nhắc người dùng cung cấp mã uỷ quyền và lưu trữ thông tin đăng nhập mới.
    • Trả về đối tượng thông tin xác thực.
  • fetchHealthData():
    • Thực hiện một lệnh gọi API đến Google Health API (thay thế ví dụ bằng các lệnh gọi phương thức cụ thể của bạn).
    • In câu trả lời.
  • Xử lý lỗi: Mã này bao gồm các khối try...catch cơ bản để xử lý lỗi.

JavaScript

  1. Cài đặt Thư viện ứng dụng API của Google:
    • Đưa thư viện vào dự án của bạn. Bạn có thể sử dụng CDN hoặc npm.
  2. Triển khai quy trình OAuth 2.0:
    • Sử dụng thư viện Dịch vụ nhận dạng của Google để xử lý quy trình OAuth (kết quả 16.1).
  3. Đưa ra yêu cầu API:
    • Sử dụng ứng dụng khách đã khởi tạo để gửi yêu cầu đến Google Health API.
  import { google } from 'https://apis.google.com/js/api.js';
  import { GoogleIdentityServices } from 'https://accounts.google.com/gsi/client';

  const CLIENT_ID = 'YOUR_CLIENT_ID';
  const API_KEY = 'YOUR_API_KEY';
  const DISCOVERY_URL = 'https://health.googleapis.com/$discovery/rest'; // Replace with actual discovery URL if needed
  const SCOPES = 'https://www.googleapis.com/auth/health'; // Add other scopes as needed

  let tokenClient;

  async function initClient() {
    await new Promise((resolve, reject) => {
      google.load('client', { callback: resolve, onerror: reject });
    });

    await google.client.init({
      apiKey: API_KEY,
      discoveryDocs: [DISCOVERY_URL],
    });

    tokenClient = await new Promise((resolve, reject) => {
        const client = GoogleIdentityServices.oauth2.initTokenClient({
            client_id: CLIENT_ID,
            scope: SCOPES,
            callback: (response) => {
              if (response && response.access_token) {
                resolve(response.access_token);
                } else {
                    reject(new Error('Failed to get token'));
                }
            },
            error_callback: (error) => {
                reject(error);
            },
      });
      resolve(client);
    });
   console.log("Client initialized");
   await authorize();
  }

  async function authorize() {
    if (google.client.getToken()) {
        console.log("Already authorized");
        return;
    }
    return await new Promise((resolve, reject) => {
        if(tokenClient){
           tokenClient.requestAccessToken();
           resolve();
        }
        else {
            reject(new Error('Token client not initialized'));
        }
    });
  }

  async function fetchHealthData() {
    try{
        await authorize();
        // Example: Replace with actual API method calls
        const response = await google.client.health.users.data.list();
        console.log('Health data:', response.result);
    } catch (error) {
        console.error('Error fetching data:', error);
    }
  }


  initClient().then(() => {
      fetchHealthData();
  });
  • Nhập thư viện:
    • https://apis.google.com/js/api.js: Tải ứng ứng dụng Google API cốt lõi.
    • https://accounts.google.com/gsi/client: Tải Dịch vụ nhận dạng của Google để xác thực.
  • Cấu hình:
    • CLIENT_ID, API_KEY: Thay thế bằng thông tin đăng nhập thực tế của bạn.
    • DISCOVERY_URL: URL để nhận định nghĩa API. Bạn có thể cần điều chỉnh thông tin này dựa trên chế độ thiết lập cuối cùng của Google Health API.
    • SCOPES: Xác định các quyền cần thiết mà ứng dụng của bạn sẽ cần (ví dụ: để đọc dữ liệu sức khoẻ).
  • initClient():
    • Tải ứng dụng Google API.
    • Khởi chạy ứng dụng bằng khoá API và tài liệu khám phá.
    • Khởi động ứng dụng mã thông báo Dịch vụ nhận dạng của Google.
  • authorize():
    • Kiểm tra xem mã thông báo đã có hay chưa.
    • Nếu không, ứng dụng sẽ gọi tokenClient.requestAccessToken() để bắt đầu quy trình OAuth.
  • fetchHealthData():
    • Gọi authorize() để đảm bảo người dùng được xác thực.
    • Thực hiện một lệnh gọi API đến Google Health API (thay thế ví dụ bằng các lệnh gọi cụ thể của bạn).
    • Ghi lại phản hồi.
  • Xử lý lỗi: Mã này bao gồm các khối try...catch cơ bản để xử lý lỗi.

Python

  1. Cài đặt Thư viện ứng dụng API của Google:
    • Sử dụng pip để cài đặt các thư viện cần thiết.
  2. Triển khai quy trình OAuth 2.0:
    • Sử dụng thư viện google-auth-oauthlib để xử lý quy trình OAuth.
  3. Đưa ra yêu cầu API:
    • Sử dụng ứng dụng khách đã khởi tạo để gửi yêu cầu đến Google Health API.
import google.auth
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
import googleapiclient.discovery
import os
import json

# --- REPLACE WITH YOUR VALUES ---
CLIENT_SECRETS_FILE = 'path/to/your/client_secret.json'
API_KEY = 'YOUR_API_KEY'
SCOPES = ['https://www.googleapis.com/auth/health']  # Add other scopes as needed
DISCOVERY_URL = 'https://health.googleapis.com/$discovery/rest'  # Adjust if needed
TOKEN_FILE = 'token.json'

def get_credentials():
    """Gets or creates OAuth 2.0 credentials."""
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists(TOKEN_FILE):
        with open(TOKEN_FILE, 'r') as token:
            creds = Credentials.from_authorized_user_info(json.load(token), SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                CLIENT_SECRETS_FILE, SCOPES
            )
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open(TOKEN_FILE, 'w') as token:
            token.write(creds.to_json())
    return creds


def create_health_client(creds):
    """Creates a Google Health API client."""
    return googleapiclient.discovery.build(
        'health',
        'v1',  # Replace with the actual API version if needed
        credentials=creds,
        discoveryServiceUrl=DISCOVERY_URL,
        developerKey=API_KEY
    )

def fetch_health_data(client):
    """Fetches health data using the API client."""
    try:
        # Example: Replace with actual API method calls
        response = client.users().data().list().execute()
        print('Health data:', response)
    except Exception as e:
        print(f'Error fetching data: {e}')


if __name__ == '__main__':
    try:
        creds = get_credentials()
        health_client = create_health_client(creds)
        fetch_health_data(health_client)
    except Exception as e:
        print(f"An error occurred: {e}")