클라이언트 라이브러리

이 페이지에서는 Google Health API에 액세스하기 위한 클라이언트 라이브러리 예시를 제공합니다.

Google Health API는 HTTP 및 JSON에 기반하므로 모든 표준 HTTP 클라이언트가 여기에 요청을 보내고 응답을 파싱할 수 있습니다.

하지만 HTTP 요청을 만들고 응답을 수동으로 파싱하는 대신 여기에 소개된 클라이언트 라이브러리 예시와 다운로드를 사용할 수도 있습니다.

자바

  1. Google API 클라이언트 라이브러리 추가:
    • Maven 또는 Gradle을 사용하여 프로젝트에 라이브러리를 포함합니다.
  2. OAuth 2.0 흐름 구현:
    • google-auth-library-java를 사용하여 OAuth 흐름을 처리합니다.
  3. API 요청:
    • 초기화된 클라이언트를 사용하여 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());
}
  • 라이브러리 가져오기:
    • com.google.api.client.*: Google API 클라이언트의 핵심 라이브러리입니다.
    • com.google.api.services.health.*: Google Health API용으로 생성된 클래스입니다. (API의 검색 문서를 기반으로 생성해야 합니다.)
  • 구성:
    • CLIENT_SECRETS_PATH: client_secret.json 파일의 경로입니다.
    • TOKENS_DIRECTORY_PATH: 토큰을 저장할 경로입니다.
    • API_KEY: API 키입니다.
    • SCOPES: 필요한 권한입니다.
    • DISCOVERY_URL: API 정의를 가져오는 URL입니다.
  • main 메서드:
    • Google Health API 클라이언트를 초기화하고 fetchHealthData를 호출합니다.
  • createHealthService():
    • 사용자 인증 정보, 앱 이름, API 키를 설정하여 Google Health API 클라이언트의 인스턴스를 만듭니다.
  • getCredentials():
    • 파일에서 클라이언트 보안 비밀번호를 로드합니다.
    • GoogleAuthorizationCodeFlow를 만듭니다.
    • 저장된 사용자 인증 정보를 로드하려고 시도합니다.
    • 사용자 인증 정보가 없거나 만료된 사용자 인증 정보가 발견되면 사용자에게 승인 코드를 묻고 새 사용자 인증 정보를 저장합니다.
    • 사용자 인증 정보 객체를 반환합니다.
  • fetchHealthData():
    • Google Health API를 호출합니다 (예를 사용자의 특정 메서드 호출로 대체).
    • 응답을 출력합니다.
  • 오류 처리: 코드에는 오류 처리를 위한 기본 try...catch 블록이 포함되어 있습니다.

자바스크립트

  1. Google API 클라이언트 라이브러리 설치:
    • 프로젝트에 라이브러리를 포함합니다. CDN 또는 npm을 사용할 수 있습니다.
  2. OAuth 2.0 흐름 구현:
    • Google ID 서비스 라이브러리를 사용하여 OAuth 흐름을 처리합니다(결과 16.1).
  3. API 요청:
    • 초기화된 클라이언트를 사용하여 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();
  });
  • 라이브러리 가져오기:
    • https://apis.google.com/js/api.js: 핵심 Google API 클라이언트를 로드합니다.
    • https://accounts.google.com/gsi/client: 인증을 위해 Google ID 서비스를 로드합니다.
  • 구성:
    • CLIENT_ID, API_KEY: 실제 사용자 인증 정보로 바꿉니다.
    • DISCOVERY_URL: API 정의를 가져올 URL입니다. 최종 Google Health API 설정에 따라 이를 조정해야 할 수도 있습니다.
    • SCOPES: 앱에 필요한 권한을 정의합니다 (예: 건강 데이터를 읽기 위한 권한).
  • initClient():
    • Google API 클라이언트를 로드합니다.
    • API 키와 검색 문서로 클라이언트를 초기화합니다.
    • Google ID 서비스 토큰 클라이언트를 초기화합니다.
  • authorize():
    • 토큰이 이미 사용 가능한지 확인합니다.
    • 그렇지 않으면 tokenClient.requestAccessToken()를 호출하여 OAuth 흐름을 시작합니다.
  • fetchHealthData():
    • 사용자가 인증되었는지 확인하기 위해 authorize()를 호출합니다.
    • Google Health API를 호출합니다 (예를 사용자의 특정 호출로 대체).
    • 응답을 로깅합니다.
  • 오류 처리: 코드에는 오류 처리를 위한 기본 try...catch 블록이 포함되어 있습니다.

Python

  1. Google API 클라이언트 라이브러리 설치:
    • pip을 사용하여 필요한 라이브러리를 설치합니다.
  2. OAuth 2.0 흐름 구현:
    • google-auth-oauthlib 라이브러리를 사용하여 OAuth 흐름을 처리합니다.
  3. API 요청:
    • 초기화된 클라이언트를 사용하여 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}")