### Open Health Connect Installation (Kotlin) Source: https://docs.spikeapi.com/sdk-docs/android/usage-guide Provides a utility to open the Google Play Store to guide the user in installing or updating the Health Connect app. This is used when `checkHealthConnectAvailability()` returns `UPDATE_REQUIRED`. ```kotlin spikeConnection.openHealthConnectInstallation() ``` -------------------------------- ### Install SpikeSDK using CocoaPods (Podfile) Source: https://docs.spikeapi.com/sdk-docs/ios/setup Integrate the Spike SDK into your Xcode project by specifying 'SpikeSDK' in your Podfile. After adding this line, run 'pod install' or 'pod update' in your terminal. ```ruby pod 'SpikeSDK' ``` -------------------------------- ### Main Function: SpikeAPI Nutrition Analysis (Go) Source: https://docs.spikeapi.com/nutrition-ai/implementation This Go main function demonstrates how to initialize and use the SpikeAPI client to perform nutrition analysis. It shows examples of both asynchronous and synchronous analysis requests, including how to handle potential errors and process the results. The synchronous analysis example further demonstrates accessing detailed nutrition information like dish name, nutri-score, and ingredients. ```go func main() { api := NewNutritionAPI("your-api-key") // Asynchronous analysis result, err := api.UploadFoodImage("path/to/food-image.jpg", UploadRequest{ IncludeIngredients: true, IncludeNutriScore: true, CountryCode: "us", }) if err != nil { fmt.Printf("Error: %v\n", err) return } fmt.Printf("Analysis started. Record ID: %s\n", result.RecordID) fmt.Printf("Status: %s\n", result.Status) // Synchronous analysis syncResult, err := api.UploadFoodImage("path/to/food-image.jpg", UploadRequest{ WaitOnProcess: true, IncludeIngredients: true, }) if err != nil { fmt.Printf("Error: %v\n", err) return } if syncResult.Status == "completed" && syncResult.Result != nil { nutrition := syncResult.Result fmt.Printf("Dish: %s\n", nutrition.DishName) fmt.Printf("Nutri-Score: %s\n", nutrition.NutriScore) for _, ingredient := range nutrition.Ingredients { fmt.Printf("- %s: %.1f%s\n", ingredient.Name, ingredient.ServingSize, ingredient.Unit) } } } ``` -------------------------------- ### Install React Native Spike SDK using Yarn Source: https://docs.spikeapi.com/sdk-docs/react-native/setup Installs the Spike SDK package for React Native using the Yarn package manager. This is the primary step for integrating the SDK into your project. ```text yarn add react-native-spike-sdk ``` -------------------------------- ### Install SpikeSDK using Swift Package Manager (Package.swift) Source: https://docs.spikeapi.com/sdk-docs/ios/setup Add the Spike SDK to your Xcode project's dependencies using Swift Package Manager. This can be done directly in your Package.swift file or via Xcode's Package Dependencies interface. ```swift dependencies: [ .package(url: "https://gitlab.com/spike_api/spike-ios-sdk", .upToNextMinor(from: "4.4.11")) ] ``` -------------------------------- ### Authenticate and Execute Lab Report Analysis Source: https://docs.spikeapi.com/lab-reports/implementation Example usage of the LabReportsAPI client, showing how to authenticate a user and perform both asynchronous and synchronous lab report uploads. ```go func main() { api := NewLabReportsAPI(9999, "HMAC_KEY_FROM_ADMIN_CONSOLE") err := api.Authenticate("my_application_user_123") if err != nil { fmt.Printf("Authentication failed: %v\n", err) return } // Asynchronous analysis result, err := api.UploadLabReport("path/to/lab-report.pdf", UploadRequest{WaitOnProcess: false}) if err == nil { fmt.Printf("Analysis started. Record ID: %s\n", result.LabReport.RecordID) } // Synchronous analysis syncResult, err := api.UploadLabReport("path/to/lab-report.pdf", UploadRequest{WaitOnProcess: true}) if err == nil && syncResult.LabReport.Status == "completed" { // Process results... } } ``` -------------------------------- ### Install MCP Proxy using Homebrew Source: https://docs.spikeapi.com/mcp-docs/desktop_clients Installs the open-source MCP proxy tool using the Homebrew package manager. This is a prerequisite for configuring desktop chat clients to interact with Spike MCP. ```bash brew install mcp-proxy ``` -------------------------------- ### Perform Localized Food Analysis Request and Response Source: https://docs.spikeapi.com/nutrition-ai/implementation An example of a full request body for analyzing an image with localization enabled, followed by the corresponding JSON response containing translated dish details and nutritional data. ```json { "include_dish_description": true, "include_ingredients": true, "wait_on_process": true, "country_code": "fr", "language_code": "fr", "body_url": "https://images.ricardocuisine.com/services/recipes/992x1340_9168.jpg" } ``` ```json { "record_id": "013501f8-da8f-88ed-8ef8-a21ad5d0e7bf", "status": "completed", "dish_name": "french omelette with mixed salad", "dish_description": "a classic French omelette made with whisked eggs, gently cooked for a soft texture, garnished with chives, served with a side of mixed green salad and a slice of toasted bread", "dish_name_translated": "Omelette française avec salade composée", "dish_description_translated": "Une omelette française classique, préparée avec des œufs battus, cuite doucement pour une texture moelleuse, garnie de ciboulette, servie avec une salade verte composée et une tranche de pain grillé.", "serving_size": 197, "unit": "g", "nutritional_fields": { "carbohydrate_g": 18.3, "energy_kcal": 288, "fat_total_g": 15.4, "protein_g": 17.3 }, "ingredients": [ { "name": "egg, whole, cooked, omelette", "name_translated": "œuf entier cuit en omelette", "serving_size": 120, "unit": "g", "nutritional_fields": { "carbohydrate_g": 2.4, "energy_kcal": 185, "fat_total_g": 14.1, "protein_g": 13.3 } } ] } ``` -------------------------------- ### Install Spike SDK Dependency Source: https://docs.spikeapi.com/sdk-docs/flutter/setup Add the Spike SDK to your Flutter project by updating the pubspec.yaml file. This dependency is required to access the SDK's health data tracking features. ```yaml dependencies: spike_flutter_sdk: ^4.3.34 ``` -------------------------------- ### POST /nutrition_records/manual Source: https://docs.spikeapi.com/nutrition-ai/implementation Upload a manually created nutrition record. ```APIDOC ## POST /nutrition_records/manual ### Description Upload a manually created nutrition record. Use this endpoint when you have the nutritional information available and want to log it without image analysis. ### Method POST ### Endpoint /nutrition_records/manual ### Parameters #### Request Body - **dish_name** (string) - Required - The name of the food item. - **serving_size** (number) - Required - The serving size. - **unit** (string) - Required - The unit for the serving size (e.g., "g", "ml", "cup"). - **nutritional_fields** (object) - Required - An object containing key nutritional information. - **energy_kcal** (number) - Calories in kcal. - **protein_g** (number) - Protein in grams. - **fat_total_g** (number) - Total fat in grams. - **carbohydrate_g** (number) - Carbohydrates in grams. - ... (other nutritional fields as needed) - **consumed_at** (string) - Optional - Timestamp when the food was consumed (ISO 8601 format). ### Request Example ```json { "dish_name": "Oatmeal", "serving_size": 150, "unit": "g", "nutritional_fields": { "energy_kcal": 300, "protein_g": 10, "fat_total_g": 5, "carbohydrate_g": 55 }, "consumed_at": "2025-09-15T08:00:00Z" } ``` ### Response #### Success Response (200) - **record_id** (string) - The unique identifier for the newly created nutrition record. - **status** (string) - The status of the record creation (e.g., "created"). - **uploaded_at** (string) - Timestamp when the record was created. - **modified_at** (string) - Timestamp when the record was last modified. #### Response Example ```json { "record_id": "c1d2e3f4-a5b6-7890-1234-567890fedcba", "status": "created", "uploaded_at": "2025-09-15T12:00:00.000Z", "modified_at": "2025-09-15T12:00:00.000Z" } ``` ``` -------------------------------- ### GET /nutrition_records/{id} Source: https://docs.spikeapi.com/nutrition-ai/implementation Retrieve a specific nutrition record by ID. ```APIDOC ## GET /nutrition_records/{id} ### Description Retrieve the details of a single, specific nutrition record using its unique identifier. ### Method GET ### Endpoint /nutrition_records/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the nutrition record to retrieve. ### Request Example ```http GET /nutrition_records/6ba7b810-9dad-11d1-80b4-00c04fd430c8 ``` ### Response #### Success Response (200) - **record_id** (string) - The unique identifier for the nutrition record. - **dish_name** (string) - The name of the detected dish. - **serving_size** (number) - The serving size of the dish. - **unit** (string) - The unit for the serving size (e.g., "g"). - **nutritional_fields** (object) - An object containing key nutritional information. - **energy_kcal** (number) - Calories in kcal. - **protein_g** (number) - Protein in grams. - **fat_total_g** (number) - Total fat in grams. - **carbohydrate_g** (number) - Carbohydrates in grams. - **uploaded_at** (string) - Timestamp when the image was uploaded. - **modified_at** (string) - Timestamp when the record was last modified. - **consumed_at** (string) - Timestamp when the food was consumed. #### Response Example ```json { "record_id": "6ba7b810-9dad-11d1-80b4-00c04fd430c8", "dish_name": "grilled chicken caesar salad", "serving_size": 275, "unit": "g", "nutritional_fields": { "energy_kcal": 292, "protein_g": 42.2, "fat_total_g": 10.9, "carbohydrate_g": 4.3 }, "uploaded_at": "2025-09-15T10:30:04.521Z", "modified_at": "2025-09-15T10:30:12.132Z", "consumed_at": "2025-09-15T10:30:04Z" } ``` ``` -------------------------------- ### GET /nutrition_records Source: https://docs.spikeapi.com/nutrition-ai/implementation Retrieve a list of nutrition records by the time range. ```APIDOC ## GET /nutrition_records ### Description Retrieve a list of all nutrition records associated with the authenticated user, filterable by a specified time range. ### Method GET ### Endpoint /nutrition_records ### Parameters #### Query Parameters - **start_date** (string) - Optional - The start date for filtering records (ISO 8601 format). - **end_date** (string) - Optional - The end date for filtering records (ISO 8601 format). ### Request Example ```http GET /nutrition_records?start_date=2025-09-14T00:00:00Z&end_date=2025-09-15T23:59:59Z ``` ### Response #### Success Response (200) - **records** (array) - A list of nutrition record objects. - Each object contains fields like `record_id`, `dish_name`, `serving_size`, `unit`, `nutritional_fields`, `uploaded_at`, `modified_at`, `consumed_at`. #### Response Example ```json { "records": [ { "record_id": "6ba7b810-9dad-11d1-80b4-00c04fd430c8", "dish_name": "grilled chicken caesar salad", "serving_size": 275, "unit": "g", "nutritional_fields": { "energy_kcal": 292, "protein_g": 42.2, "fat_total_g": 10.9, "carbohydrate_g": 4.3 }, "uploaded_at": "2025-09-15T10:30:04.521Z", "modified_at": "2025-09-15T10:30:12.132Z", "consumed_at": "2025-09-15T10:30:04Z" }, { "record_id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "dish_name": "Oatmeal", "serving_size": 150, "unit": "g", "nutritional_fields": { "energy_kcal": 300, "protein_g": 10, "fat_total_g": 5, "carbohydrate_g": 55 }, "uploaded_at": "2025-09-15T12:00:00.000Z", "modified_at": "2025-09-15T12:00:00.000Z", "consumed_at": "2025-09-15T08:00:00Z" } ] } ``` ``` -------------------------------- ### Configure OpenAI with SpikeAPI MCP Tool Source: https://docs.spikeapi.com/mcp-docs/implementation Demonstrates how to set up an OpenAI request that integrates with the SpikeAPI health data server. This allows the model to access and analyze wearable device data using the MCP protocol. ```bash curl -X POST "https://api.openai.com/v1/responses" \ -H "Authorization: Bearer OPENAPI_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "o4-mini", "instructions": "you are a health and wellness analyst.", "input": "Analyze my health data for 2025-08-17 and provide a summary of my health data.", "tools": [ { "type": "mcp", "server_label": "spike-health-data", "server_url": "https://app-api.spikeapi.com/v3/mcp", "headers": { "Authorization": "Bearer SPIKE_ACCESS_TOKEN" }, "server_description": "Health and fitness data analysis server providing daily and hourly statistics from connected wearables and health devices.", "require_approval": "never" } ], "tool_choice": "auto", "max_tool_calls": 1, "max_output_tokens": 5000, "parallel_tool_calls": true, "metadata": { "analysis_type": "daily_health_review", "date": "2025-08-17", "tools_used": "mcp_health_data", "version": "1.0.0" } }' ``` ```go package main import ( "context" "fmt" "log" "os" openai "github.com/openai/openai-go/v2" "github.com/openai/openai-go/v2/option" "github.com/openai/openai-go/v2/responses" ) func main() { openaiKey := os.Getenv("OPENAI_API_KEY") spikeToken := os.Getenv("SPIKE_ACCESS_TOKEN") if openaiKey == "" || spikeToken == "" { log.Fatal("OPENAI_API_KEY and SPIKE_ACCESS_TOKEN environment variables are required") } client := openai.NewClient(option.WithAPIKey(openaiKey)) mcpTool := responses.ToolUnionParam{ OfMcp: &responses.ToolMcpParam{ Type: "mcp", ServerLabel: "spike-health-data", ServerURL: "https://app-api.spikeapi.com/v3/mcp", Headers: map[string]string{ "Authorization": fmt.Sprintf("Bearer %s", spikeToken), }, ServerDescription: openai.String("Health and fitness data analysis server"), RequireApproval: responses.ToolMcpRequireApprovalUnionParam{ OfMcpToolApprovalSetting: openai.String("never"), }, }, } request := responses.ResponseNewParams{ Model: responses.ChatModelO4Mini, Instructions: openai.String("You are a health data analyst. Use the available tools to analyze the user's health data and provide insights."), Input: responses.ResponseNewParamsInputUnion{ OfString: openai.String("Analyze my sleep data for the past 3 days and give me a brief summary of my sleep patterns."), }, Tools: []responses.ToolUnionParam{mcpTool}, ToolChoice: responses.ResponseNewParamsToolChoiceUnion{ OfToolChoiceMode: openai.Opt(responses.ToolChoiceOptionsAuto), }, MaxOutputTokens: openai.Opt(int64(1000)), MaxToolCalls: openai.Opt(int64(3)), ParallelToolCalls: openai.Opt(true), } ctx := context.Background() response, err := client.Responses.New(ctx, request) if err != nil { log.Fatalf("API call failed: %v", err) } fmt.Println("=== Health Data Analysis ===") fmt.Println(response.OutputText()) } ``` ```python import os import sys from openai import OpenAI def main(): openai_key = os.getenv("OPENAI_API_KEY") spike_token = os.getenv("SPIKE_ACCESS_TOKEN") if not openai_key or not spike_token: print("Error: OPENAI_API_KEY and SPIKE_ACCESS_TOKEN environment variables are required") sys.exit(1) client = OpenAI(api_key=openai_key) mcp_tool = { "type": "mcp", "server_label": "spike-health-data", "server_url": "https://app-api.spikeapi.com/v3/mcp", "headers": { "Authorization": f"Bearer {spike_token}" }, "server_description": "Health and fitness data analysis server", "require_approval": "never" } try: response = client.responses.create( model="gpt-4o", input=[{"role": "user", "content": "Analyze my sleep data for the past 3 days."}] ) except Exception as e: print(f"API call failed: {e}") ``` -------------------------------- ### SpikeAPI Client Implementation (Go) Source: https://docs.spikeapi.com/lab-reports/implementation This Go code implements a client for the SpikeAPI, handling authentication via HMAC and providing methods to upload lab reports. It defines data structures for requests and responses, including detailed lab report information. Dependencies include standard Go libraries for HTTP, JSON, crypto, and file operations. ```go package main import ( "bytes" "crypto/hmac" "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" "fmt" "io" "net/http" "os" "time" ) type LabReportsAPI struct { BaseURL string ApplicationID int64 HMACKey string AccessToken string } type UploadRequest struct { Body string `json:"body"` MimeType string `json:"mime_type"` Filename string `json:"filename"` WaitOnProcess bool `json:"wait_on_process"` } type LabReportResponse struct { LabReport LabReport `json:"lab_report"` } type LabReport struct { RecordID string `json:"record_id"` Status string `json:"status"` CollectionDate string `json:"collection_date"` ResultDate string `json:"result_date"` Sections []LabSection `json:"sections"` UploadedAt time.Time `json:"uploaded_at"` } type LabSection struct { LoincCode string `json:"loinc_code"` LoincCommonName string `json:"loinc_common_name"` OriginalSectionName string `json:"original_section_name"` Results []LabResult `json:"results"` } type LabResult struct { LoincCode string `json:"loinc_code"` LoincCommonName string `json:"loinc_common_name"` OriginalTestName string `json:"original_test_name"` OriginalUnitName string `json:"original_unit_name"` StandardUnitName string `json:"standard_unit_name"` Value *float64 `json:"value,omitempty"` ValueText *string `json:"value_text,omitempty"` WithinNormalRange *bool `json:"within_normal_range,omitempty"` NormalMin *float64 `json:"normal_min,omitempty"` NormalMax *float64 `json:"normal_max,omitempty"` RequireHumanReview bool `json:"require_human_review,omitempty"` } func NewLabReportsAPI(applicationID int64, hmacKey string) *LabReportsAPI { return &LabReportsAPI{ BaseURL: "https://api.spikeapi.com", ApplicationID: applicationID, HMACKey: hmacKey, } } func (api *LabReportsAPI) Authenticate(userID string) error { // Generate HMAC signature h := hmac.New(sha256.New, []byte(api.HMACKey)) h.Write([]byte(userID)) signature := hex.EncodeToString(h.Sum(nil)) // Prepare authentication request authBody := map[string]interface{}{ "application_id": api.ApplicationID, "application_user_id": userID, "signature": signature, } bodyBytes, err := json.Marshal(authBody) if err != nil { return fmt.Errorf("failed to marshal auth request: %w", err) } // Make an authentication request req, err := http.NewRequest("POST", api.BaseURL+"/auth/hmac", bytes.NewBuffer(bodyBytes)) if err != nil { return fmt.Errorf("failed to create auth request: %w", err) } req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "application/json") client := &http.Client{Timeout: 30 * time.Second} resp, err := client.Do(req) if err != nil { return fmt.Errorf("auth request failed: %w", err) } defer resp.Body.Close() if resp.StatusCode != 200 { return fmt.Errorf("authentication failed with status %d", resp.StatusCode) } // Parse response respBody, err := io.ReadAll(resp.Body) if err != nil { return fmt.Errorf("failed to read auth response: %w", err) } var authResp map[string]string if err := json.Unmarshal(respBody, &authResp); err != nil { return fmt.Errorf("failed to parse auth response: %w", err) } api.AccessToken = authResp["access_token"] return nil } func (api *LabReportsAPI) createAuthHeaders() map[string]string { if api.AccessToken == "" { panic("Access token not available. Call Authenticate() first.") } return map[string]string{ "Content-Type": "application/json", "Authorization": "Bearer " + api.AccessToken, } } func (api *LabReportsAPI) UploadLabReport(documentPath string, options UploadRequest) (*LabReportResponse, error) { // Read and encode document documentData, err := os.ReadFile(documentPath) ``` -------------------------------- ### Get Records Source: https://docs.spikeapi.com/sdk-docs/android/usage-guide Retrieves all records from a specified provider, such as Garmin. ```APIDOC ## GET /records ### Description Get all records we have from Garmin provider. ### Method GET ### Endpoint /records ### Parameters #### Query Parameters - **types** (Set) - Required - The types of records to retrieve (e.g., STEPS_TOTAL, CALORIES_BURNED_TOTAL). - **from** (Instant) - Required - The start time for the record retrieval. - **to** (Instant) - Required - The end time for the record retrieval. - **filter** (StatisticsFilter) - Optional - Filters for the records, such as specifying providers. ### Request Example ```kotlin val records = spikeConnection.getRecords( types = setOf(MetricType.STEPS_TOTAL, MetricType.CALORIES_BURNED_TOTAL), from = LocalDate.now().minusWeeks(1).atStartOfDay(ZoneId.systemDefault()).toInstant(), to = Instant.now(), filter = StatisticsFilter(providers = listOf(Provider.HEALTH_CONNECT)) ) ``` ### Response #### Success Response (200) - **records** (List) - A list of record objects. #### Response Example ```json { "records": [ { "type": "STEPS_TOTAL", "value": 10000, "timestamp": "2023-10-27T00:00:00Z" }, { "type": "CALORIES_BURNED_TOTAL", "value": 500, "timestamp": "2023-10-27T00:00:00Z" } ] } ``` ``` -------------------------------- ### GET /lab_reports Source: https://docs.spikeapi.com/lab-reports/implementation Retrieves a list of lab reports filtered by a specific time range. ```APIDOC ## GET /lab_reports ### Description Retrieves a list of lab reports based on the provided time range parameters. ### Method GET ### Endpoint /lab_reports ### Parameters #### Query Parameters - **start_date** (string) - Optional - ISO 8601 start date for filtering. - **end_date** (string) - Optional - ISO 8601 end date for filtering. ### Response #### Success Response (200) - **reports** (array) - A list of lab report summary objects. ``` -------------------------------- ### POST /nutrition_records/manual Source: https://docs.spikeapi.com/api-reference/upload-nutrition-record Upload a manually created nutrition record to the system. ```APIDOC ## POST /nutrition_records/manual ### Description Uploads a manually created nutrition record. The record is validated against the schema, and mandatory fields are enforced. The status is set to 'completed' and input type to 'manual'. ### Method POST ### Endpoint https://app-api.spikeapi.com/v3/nutrition_records/manual ### Parameters #### Request Body - **consumed_at** (string, date-time) - Optional - UTC time when food was consumed. - **dish_name** (string) - Required - The name of the dish. - **dish_name_translated** (string) - Optional - Dish name in the local language. - **dish_description** (string) - Optional - Detected dish description. - **dish_description_translated** (string) - Optional - Dish description translated to target language. - **nutri_score** (string) - Optional - Nutri-Score (A-E). - **ingredients** (array) - Optional - List of detected ingredients. ### Request Example { "dish_name": "beef and broccoli stir-fry", "dish_name_translated": "Rindfleisch und Brokkoli Pfanne", "consumed_at": "2025-09-15T10:30:12Z" } ### Response #### Success Response (200) - **dish_name** (string) - The name of the dish. - **input_type** (string) - The input type (manual). - **modified_at** (string) - Update timestamp in UTC. #### Response Example { "dish_name": "beef and broccoli stir-fry", "input_type": "manual", "modified_at": "2025-09-15T10:30:12.132Z" } ``` -------------------------------- ### GET /lab_reports Source: https://docs.spikeapi.com/lab-reports/implementation Retrieves a list of all uploaded lab reports within a specified time range. ```APIDOC ## GET /lab_reports ### Description Retrieves a list of all uploaded lab reports. ### Method GET ### Endpoint `/lab_reports` ### Parameters #### Query Parameters - **start_date** (string) - Optional - The start of the time range for filtering reports (e.g., YYYY-MM-DD). - **end_date** (string) - Optional - The end of the time range for filtering reports (e.g., YYYY-MM-DD). ``` -------------------------------- ### Upload and Process Lab Reports in Go Source: https://docs.spikeapi.com/lab-reports/implementation Demonstrates how to upload a PDF lab report by encoding it to base64 and sending a POST request to the SpikeAPI. It handles both asynchronous and synchronous processing modes and parses the resulting lab report data. ```go func (api *LabReportsAPI) UploadLabReport(filePath string, options UploadRequest) (*LabReportResponse, error) { documentData, err := os.ReadFile(filePath) if err != nil { return nil, fmt.Errorf("failed to read document: %w", err) } options.Body = base64.StdEncoding.EncodeToString(documentData) if options.MimeType == "" { options.MimeType = "application/pdf" } if options.Filename == "" { options.Filename = "lab_report.pdf" } bodyBytes, err := json.Marshal(options) if err != nil { return nil, fmt.Errorf("failed to marshal request: %w", err) } req, err := http.NewRequest("POST", api.BaseURL+"/lab_reports", bytes.NewBuffer(bodyBytes)) if err != nil { return nil, fmt.Errorf("failed to create request: %w", err) } authHeaders := api.createAuthHeaders() for key, value := range authHeaders { req.Header.Set(key, value) } client := &http.Client{Timeout: 60 * time.Second} resp, err := client.Do(req) if err != nil { return nil, fmt.Errorf("request failed: %w", err) } defer resp.Body.Close() respBody, err := io.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("failed to read response: %w", err) } var result LabReportResponse if err := json.Unmarshal(respBody, &result); err != nil { return nil, fmt.Errorf("failed to parse response: %w", err) } return &result, nil } ``` -------------------------------- ### GET /lab_reports/{lab_report_id} Source: https://docs.spikeapi.com/lab-reports/implementation Retrieves the status and results for a specific lab report using its ID. ```APIDOC ## GET /lab_reports/{lab_report_id} ### Description Retrieves the status and results for a specific lab report. ### Method GET ### Endpoint `/lab_reports/{lab_report_id}` ### Parameters #### Path Parameters - **lab_report_id** (string) - Required - The unique identifier for the lab report. ``` -------------------------------- ### Upload and Analyze Food Images via SpikeAPI Source: https://docs.spikeapi.com/nutrition-ai/implementation Demonstrates how to upload food images for nutritional analysis. Supports both asynchronous processing (returning a record ID) and synchronous processing (waiting for full nutritional data). ```javascript async function analyzeFood() { const api = new NutritionAPI('your-api-key'); try { // Asynchronous analysis (recommended) const result = await api.uploadFoodImage('path/to/food-image.jpg', { includeIngredients: true, includeNutriScore: true, countryCode: 'us' }); console.log(`Analysis started. Record ID: ${result.record_id}`); // Synchronous analysis (wait for results) const syncResult = await api.uploadFoodImage('path/to/food-image.jpg', { waitOnProcess: true, includeIngredients: true }); if (syncResult.status === 'completed') { console.log(`Dish: ${syncResult.result.dish_name}`); } } catch (error) { console.error('Error:', error.message); } } ``` ```go func (api *NutritionAPI) UploadFoodImage(imagePath string, options UploadRequest) (*UploadResponse, error) { imageData, err := os.ReadFile(imagePath) if err != nil { return nil, fmt.Errorf("failed to read image: %w", err) } options.Body = base64.StdEncoding.EncodeToString(imageData) // Implementation continues with HTTP POST request to api.BaseURL return nil, nil } ``` -------------------------------- ### GET /lab_reports/{lab_report_id} Source: https://docs.spikeapi.com/lab-reports/implementation Retrieves the full details of a specific lab report by its unique identifier. ```APIDOC ## GET /lab_reports/{lab_report_id} ### Description Retrieves the complete analysis data for a specific lab report using its ID. ### Method GET ### Endpoint /lab_reports/{lab_report_id} ### Parameters #### Path Parameters - **lab_report_id** (string) - Required - The unique identifier of the lab report. ### Response #### Success Response (200) - **lab_report** (object) - The detailed lab report object. ``` -------------------------------- ### Get Records Source: https://docs.spikeapi.com/sdk-docs/ios/usage-guide Retrieves raw data points collected from user devices or applications. ```APIDOC ## GET /getRecords ### Description Fetches raw health records for specific metrics within a defined time range. ### Method GET ### Parameters #### Query Parameters - **types** (Array) - Required - List of metric types to retrieve. - **from** (Date) - Required - Start date for the data range. - **to** (Date) - Required - End date for the data range. ### Response #### Success Response (200) - **Array** (Array) - A list of raw record objects containing metadata, metrics, and source information. ``` -------------------------------- ### Initialize Spike SDK at App Startup (Swift) Source: https://docs.spikeapi.com/sdk-docs/flutter/background-delivery Initializes the Spike SDK when the application launches. This is a prerequisite for background delivery to function correctly on iOS. Ensure this code is placed within your AppDelegate's `didFinishLaunchingWithOptions` method. ```swift import SpikeSDK ... override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { ... Spike.configure() ... } ... ``` -------------------------------- ### Get Statistics Source: https://docs.spikeapi.com/sdk-docs/ios/usage-guide Retrieves aggregated health statistics such as steps or distance over a specified time range. ```APIDOC ## GET /getStatistics ### Description Fetches daily statistics for various health metrics derived from Apple Health. ### Method GET ### Parameters #### Query Parameters - **types** (Array) - Required - List of statistics types to retrieve (e.g., steps, distance_total). - **from** (Date) - Required - Start date for the data range. - **to** (Date) - Required - End date for the data range (max 90 days). - **interval** (String) - Required - Granularity of data (hour or day). - **filter** (Object) - Optional - Filtering options including providers and manual entry exclusion. ### Response #### Success Response (200) - **Array** (Array) - A list of statistic objects containing start, end, duration, type, and value. ``` -------------------------------- ### Get Daily Statistics Source: https://docs.spikeapi.com/sdk-docs/android/usage-guide Retrieves daily statistics for steps and total distance from health Connect. ```APIDOC ## GET /statistics ### Description Get daily statistics for steps and total distance from health Connect. ### Method GET ### Endpoint /statistics ### Parameters #### Query Parameters - **types** (Set) - Required - The types of statistics to retrieve (e.g., STEPS, DISTANCE_TOTAL). - **from** (Instant) - Required - The start time for the statistics retrieval. - **to** (Instant) - Required - The end time for the statistics retrieval. - **interval** (StatisticsInterval) - Required - The interval for the statistics (e.g., DAY). - **filter** (StatisticsFilter) - Optional - Filters for the statistics, such as specifying providers. ### Request Example ```kotlin val dailyStatistics = spikeConnection.getStatistics( types = setOf(StatisticsType.STEPS, StatisticsType.DISTANCE_TOTAL), from = LocalDate.now().minusWeeks(1).atStartOfDay(ZoneId.systemDefault()).toInstant(), to = Instant.now(), interval = StatisticsInterval.DAY, filter = StatisticsFilter(providers = listOf(Provider.HEALTH_CONNECT)) ) ``` ### Response #### Success Response (200) - **statistics** (List) - A list of daily statistics objects. #### Response Example ```json { "statistics": [ { "type": "STEPS", "value": 10000, "timestamp": "2023-10-27T00:00:00Z" }, { "type": "DISTANCE_TOTAL", "value": 5000, "timestamp": "2023-10-27T00:00:00Z" } ] } ``` ``` -------------------------------- ### Add Spike SDK Maven Repository to Gradle Source: https://docs.spikeapi.com/sdk-docs/android/setup Configures your project's build.gradle file to include the Spike SDK Maven repository. This allows Gradle to download the SDK artifacts. Ensure this is placed within the 'allprojects' block. ```gradle allprojects { repositories { // Other repositories maven { url 'https://gitlab.com/api/v4/projects/43396247/packages/maven' } } } ``` -------------------------------- ### Get Nutrition Record Source: https://docs.spikeapi.com/nutrition-ai/implementation Retrieve the details of a specific nutrition record using its ID. This is useful for checking the status of asynchronous processing or viewing record details. ```APIDOC ## GET /nutrition_records/{id} ### Description Retrieve the details of a specific nutrition record using its ID. This endpoint can be used to check the status of asynchronous processing or to view the analyzed nutritional information. ### Method GET ### Endpoint `/nutrition_records/{id}` ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the nutrition record to retrieve. #### Query Parameters None #### Request Body None ### Request Example (No request body for GET requests) ### Response #### Success Response (200) - **id** (string) - The ID of the nutrition record. - **status** (string) - The processing status of the record (e.g., 'completed', 'processing'). - **nutritional_info** (object) - The analyzed nutritional information (if available). #### Response Example ```json { "id": "record_789", "status": "completed", "nutritional_info": { "calories": 350, "protein": 15, "carbohydrates": 40, "fat": 15 } } ``` ``` -------------------------------- ### Analyze Health Data via SpikeAPI MCP Tools Source: https://docs.spikeapi.com/mcp-docs/implementation Demonstrates how to initialize an OpenAI client with MCP tool configurations to perform health data analysis. The code handles API requests, processes tool-based responses, and logs token usage statistics. ```python try: response = client.responses.create( model="o1-mini", instructions="You are a health data analyst. Use the available tools to analyze the user's health data and provide insights.", tools=[mcp_tool], max_tokens=1000 ) print("=== Health Data Analysis ===") print(response.output[0].content) if hasattr(response, 'usage'): usage = response.usage print(f"\nTokens used - Input: {usage.prompt_tokens}, Output: {usage.completion_tokens}, Total: {usage.total_tokens}") except Exception as e: print(f"API call failed: {e}") sys.exit(1) ``` ```typescript const mcpTool = { type: 'mcp', server_label: 'spike-health-data', server_url: 'https://app-api.spikeapi.com/v3/mcp', headers: { 'Authorization': `Bearer ${spikeToken}` }, server_description: 'Health and fitness data analysis server', require_approval: 'never' }; try { const response = await client.responses.create({ model: 'o1-mini', instructions: 'You are a health data analyst. Use the available tools to analyze the user\'s health data and provide insights.', input: 'Analyze my sleep data for the past 3 days and give me a brief summary of my sleep patterns.', tools: [mcpTool], tool_choice: 'auto', max_output_tokens: 1000, max_tool_calls: 3, parallel_tool_calls: true }); console.log('=== Health Data Analysis ==='); console.log(response.output_text); const usage = response.usage; console.log(`\nTokens used - Input: ${usage.input_tokens}, Output: ${usage.output_tokens}, Total: ${usage.total_tokens}`); } catch (error) { console.error(`API call failed: ${error.message}`); process.exit(1); } ``` -------------------------------- ### POST /nutrition_records/manual Source: https://docs.spikeapi.com/api-reference/nutrition-ai-upload-nutrition-record Uploads a manually created nutrition record to the system. The record is validated against the schema and marked as completed. ```APIDOC ## POST /nutrition_records/manual ### Description Upload a manually created nutrition record. The values are validated against the schema, and the record status is set to 'completed' with an input type of 'manual'. ### Method POST ### Endpoint https://app-api.spikeapi.com/v3/nutrition_records/manual ### Parameters #### Request Body - **consumed_at** (string, date-time) - Optional - The UTC time when food was consumed. - **dish_name** (string) - Required - The name of the dish. - **dish_name_translated** (string) - Optional - The dish name in the local language. - **dish_description** (string) - Optional - Detected dish description. - **dish_description_translated** (string) - Optional - Dish description translated to target language. - **nutri_score** (string) - Optional - Nutri-Score (A-E). - **ingredients** (array) - Optional - List of detected ingredients. ### Request Example { "dish_name": "beef and broccoli stir-fry", "consumed_at": "2025-09-15T10:30:12Z" } ### Response #### Success Response (200) - **dish_name** (string) - The name of the dish. - **input_type** (string) - The input type (manual). - **modified_at** (string) - Update timestamp in UTC. #### Response Example { "dish_name": "beef and broccoli stir-fry", "input_type": "manual", "modified_at": "2025-09-15T10:30:12.132Z" } ``` -------------------------------- ### Initialize Spike SDK in AppDelegate Source: https://docs.spikeapi.com/sdk-docs/ios/background-delivery Configures the Spike SDK during application startup. This should be implemented within the application:didFinishLaunchingWithOptions: method of the AppDelegate. ```swift import SpikeSDK func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { Spike.configure() return true } ``` -------------------------------- ### Implement Android 14 Permission Usage Activity Alias Source: https://docs.spikeapi.com/sdk-docs/android/setup Required for Android 14 compatibility, this activity-alias acts as a wrapper to handle permission usage views within the AndroidManifest.xml. ```xml ``` -------------------------------- ### Integration Settings Source: https://docs.spikeapi.com/api-docs/configuration Configuration parameters for managing redirects, webhooks, and data backfill policies. ```APIDOC ## Integration Configuration ### Description Settings configured in the admin console to manage how Spike API handles data synchronization and user redirects. ### Configuration Parameters - **Default Redirect URL** (String) - Required: Fallback URL for provider integration completions. - **Allowed Redirect Domains** (Array) - Optional: Whitelist of domains allowed for dynamic redirects to prevent security attacks. - **Main Webhook URL** (String) - Required: Endpoint for receiving real-time notifications on user data changes. - **Max Backfill (days)** (Integer) - Required: Number of days of historical data to fetch upon initial provider connection (Max: 90). ### Webhook Requirements - **Response**: Must return HTTP 200 within 30 seconds. - **Security**: Validate requests using the Webhook Signature Key. ### Redirect Placeholders - `{application_user_id}`: Your internal user ID. - `{provider_slug}`: The provider name (e.g., "garmin"). - `{provider_user_id}`: The provider's unique user ID. ```