ক্লায়েন্ট লাইব্রেরি

এই পৃষ্ঠায় গুগল হেলথ এপিআই অ্যাক্সেস করার জন্য ক্লায়েন্ট লাইব্রেরির উদাহরণ দেওয়া হয়েছে।

গুগল হেলথ এপিআই HTTP এবং JSON-এর উপর ভিত্তি করে তৈরি, তাই যেকোনো সাধারণ HTTP ক্লায়েন্ট এতে অনুরোধ পাঠাতে এবং প্রতিক্রিয়াগুলো পার্স করতে পারে।

তবে, ম্যানুয়ালি HTTP রিকোয়েস্ট তৈরি এবং রেসপন্স পার্স করার পরিবর্তে, আপনি এখানে দেওয়া ক্লায়েন্ট লাইব্রেরির উদাহরণ এবং ডাউনলোডগুলো ব্যবহার করতে পারেন।

জাভা

  1. গুগল এপিআই ক্লায়েন্ট লাইব্রেরি যোগ করুন:
    • আপনার প্রজেক্টে লাইব্রেরিটি অন্তর্ভুক্ত করুন (Maven বা Gradle ব্যবহার করে)।
  2. OAuth 2.0 ফ্লো বাস্তবায়ন করুন:
    • OAuth ফ্লো পরিচালনা করতে google-auth-library-java ব্যবহার করুন।
  3. এপিআই অনুরোধ করুন:
    • 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.* : গুগল এপিআই ক্লায়েন্টের জন্য মূল লাইব্রেরিসমূহ।
    • com.google.api.services.health.* : গুগল হেলথ এপিআই-এর জন্য তৈরি ক্লাসসমূহ। (এপিআই-এর ডিসকভারি ডকুমেন্টের উপর ভিত্তি করে আপনাকে এটি তৈরি করতে হবে)।
  • কনফিগারেশন:
    • CLIENT_SECRETS_PATH : আপনার client_secret.json ফাইলের পাথ।
    • TOKENS_DIRECTORY_PATH : টোকেনগুলো সংরক্ষণের পাথ।
    • API_KEY : আপনার এপিআই কী।
    • SCOPES : প্রয়োজনীয় অনুমতিসমূহ।
    • DISCOVERY_URL : এপিআই সংজ্ঞা পাওয়ার জন্য ইউআরএল।
  • main পদ্ধতি:
    • গুগল হেলথ এপিআই ক্লায়েন্ট চালু করে এবং fetchHealthData কল করে।
  • createHealthService() :
    • ক্রেডেনশিয়াল, অ্যাপের নাম এবং এপিআই কী সেট করে গুগল হেলথ এপিআই ক্লায়েন্টের একটি ইনস্ট্যান্স তৈরি করে।
  • getCredentials() :
    • ফাইল থেকে ক্লায়েন্টের গোপনীয় তথ্য লোড করে।
    • একটি GoogleAuthorizationCodeFlow তৈরি করে।
    • সংরক্ষিত পরিচয়পত্র লোড করার প্রচেষ্টা।
    • যদি কোনো ক্রেডেনশিয়াল খুঁজে না পাওয়া যায় বা ক্রেডেনশিয়ালের মেয়াদ শেষ হয়ে যায়, তাহলে ব্যবহারকারীর কাছে অনুমোদন কোড চাওয়া হয় এবং নতুন ক্রেডেনশিয়ালগুলো সংরক্ষণ করা হয়।
    • ক্রেডেনশিয়ালস অবজেক্টটি ফেরত দেয়।
  • fetchHealthData() :
    • গুগল হেলথ এপিআই-তে একটি এপিআই কল করে (উদাহরণটি আপনার নির্দিষ্ট মেথড কল দিয়ে প্রতিস্থাপন করুন)।
    • প্রতিক্রিয়াটি প্রিন্ট করে।
  • ত্রুটি পরিচালনা: কোডটিতে ত্রুটি পরিচালনার জন্য সাধারণ try...catch ব্লক অন্তর্ভুক্ত রয়েছে।

জাভাস্ক্রিপ্ট

  1. গুগল এপিআই ক্লায়েন্ট লাইব্রেরি ইনস্টল করুন:
    • আপনার প্রজেক্টে লাইব্রেরিটি অন্তর্ভুক্ত করুন। আপনি CDN বা npm ব্যবহার করতে পারেন।
  2. OAuth 2.0 ফ্লো বাস্তবায়ন করুন:
    • OAuth ফ্লো পরিচালনা করতে Google Identity Services লাইব্রেরি ব্যবহার করুন ( ফলাফল ১৬.১ )।
  3. এপিআই অনুরোধ করুন:
    • 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 : গুগলের মূল এপিআই ক্লায়েন্ট লোড করে।
    • https://accounts.google.com/gsi/client : প্রমাণীকরণের জন্য গুগল আইডেন্টিটি সার্ভিসেস লোড করে।
  • কনফিগারেশন:
    • CLIENT_ID , API_KEY : আপনার আসল ক্রেডেনশিয়াল দিয়ে প্রতিস্থাপন করুন।
    • DISCOVERY_URL : এপিআই ডেফিনিশন পাওয়ার জন্য ইউআরএল। চূড়ান্ত গুগল হেলথ এপিআই সেটআপের উপর ভিত্তি করে আপনাকে এটি পরিবর্তন করতে হতে পারে।
    • SCOPES : আপনার অ্যাপের প্রয়োজনীয় অনুমতিগুলো নির্ধারণ করুন (যেমন, স্বাস্থ্য সংক্রান্ত ডেটা পড়ার অনুমতি)।
  • initClient() :
    • গুগল এপিআই ক্লায়েন্ট লোড করে।
    • আপনার এপিআই কী এবং ডিসকভারি ডকুমেন্ট ব্যবহার করে ক্লায়েন্টটি চালু করে।
    • গুগল আইডেন্টিটি সার্ভিসেস টোকেন ক্লায়েন্ট চালু করে।
  • authorize() :
    • টোকেন আগে থেকেই আছে কিনা তা যাচাই করে।
    • অন্যথায়, এটি OAuth ফ্লো শুরু করার জন্য tokenClient.requestAccessToken() কল করে।
  • fetchHealthData() :
    • ব্যবহারকারীর প্রমাণীকরণ নিশ্চিত করতে authorize() ফাংশনটি কল করা হয়।
    • গুগল হেলথ এপিআই-তে একটি এপিআই কল করে (উদাহরণটি আপনার নির্দিষ্ট কল দিয়ে প্রতিস্থাপন করুন)।
    • প্রতিক্রিয়াটি নথিভুক্ত করে।
  • ত্রুটি পরিচালনা: কোডটিতে ত্রুটি পরিচালনার জন্য সাধারণ try...catch ব্লক অন্তর্ভুক্ত রয়েছে।

পাইথন

  1. গুগল এপিআই ক্লায়েন্ট লাইব্রেরি ইনস্টল করুন:
    • প্রয়োজনীয় লাইব্রেরিগুলো ইনস্টল করতে pip ব্যবহার করুন।
  2. OAuth 2.0 ফ্লো বাস্তবায়ন করুন:
    • OAuth প্রবাহ পরিচালনা করতে google-auth-oauthlib লাইব্রেরিটি ব্যবহার করুন।
  3. এপিআই অনুরোধ করুন:
    • 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}")