### Multi-Region Setup Example Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/configuration.md An example demonstrating how to configure multiple regions for primary, secondary, and fallback hosts. ```dart final options = ClientOptions( hosts: [ // Primary region Host(url: 'us-1.algolia.net', callType: CallType.read), Host(url: 'us-1.algolia.net', callType: CallType.write), // Secondary region Host(url: 'eu-1.algolia.net'), // Fallback Host(url: 'fallback.algolia.net'), ], ); ``` -------------------------------- ### Multi-Client Application Setup with Algolia Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/configuration.md This example demonstrates a singleton pattern for managing multiple Algolia clients (SearchClient and InsightsClient) within an application. It centralizes configuration and provides a single point of access. ```dart class AlgoliaClients { static final _instance = AlgoliaClients._(); late final SearchClient searchClient; late final InsightsClient insightsClient; factory AlgoliaClients() => _instance; AlgoliaClients._() { const appId = 'YOUR_APP_ID'; final commonOptions = ClientOptions( connectTimeout: Duration(seconds: 5), readTimeout: Duration(seconds: 10), compression: 'gzip', logger: _log, ); searchClient = SearchClient( appId: appId, apiKey: 'SEARCH_API_KEY', options: commonOptions, ); insightsClient = InsightsClient( appId: appId, apiKey: 'INSIGHTS_API_KEY', options: commonOptions, region: 'de', ); } static void _log(Object? msg) { developer.log(msg.toString(), level: 800, name: 'algolia'); } } // Usage final clients = AlgoliaClients(); await clients.searchClient.search(...); ``` -------------------------------- ### Minimal Algolia SearchClient Setup (Development) Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/configuration.md This snippet shows the most basic setup for initializing the SearchClient for development purposes. It requires only the application ID and API key. ```dart void main() { final client = SearchClient( appId: 'YOUR_APP_ID', apiKey: 'YOUR_API_KEY', ); } ``` -------------------------------- ### Recommended Algolia SearchClient Setup (Production) Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/configuration.md This is the recommended production setup for the SearchClient, including client options for timeouts, custom headers, and a production logger. Ensure to replace 'productionLogger' with your actual logging implementation. ```dart void main() { final client = SearchClient( appId: 'YOUR_APP_ID', apiKey: 'YOUR_API_KEY', options: ClientOptions( connectTimeout: Duration(seconds: 5), readTimeout: Duration(seconds: 10), writeTimeout: Duration(seconds: 30), headers: { 'User-Agent': 'MyApp/1.0', }, logger: productionLogger, compression: 'gzip', ), ); } void productionLogger(Object? message) { developer.log( message.toString(), level: 800, name: 'algolia', ); } ``` -------------------------------- ### Install Dependencies and Run Tests with Melos Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/AGENTS.md Use Melos to install project dependencies and execute tests across all packages. Ensure the Dart SDK is installed. ```bash cd clients/algoliasearch-client-dart melos bootstrap melos run test ``` -------------------------------- ### GDPR-Compliant Algolia Setup (EU) Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/configuration.md This setup configures the SearchClient to use EU data centers and initializes an InsightsClient with a specified EU region ('de') for GDPR compliance. Ensure your application's data residency requirements are met. ```dart final searchClient = SearchClient( appId: 'YOUR_APP_ID', apiKey: 'YOUR_API_KEY', options: ClientOptions( hosts: [ Host(url: 'algolia.eu-west-1.algolia.net'), ], ), ); final insightsClient = InsightsClient( appId: 'YOUR_APP_ID', apiKey: 'YOUR_API_KEY', region: 'de', // EU data residency ); ``` -------------------------------- ### Usage Example: Search and Track User Interactions Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/insights-client.md Demonstrates initializing SearchClient and InsightsClient, performing a search with click analytics, and tracking user events like clicks and conversions. ```dart import 'package:algolia_client_insights/algolia_client_insights.dart'; import 'package:algolia_client_search/algolia_client_search.dart'; void main() async { // Initialize clients final searchClient = SearchClient(appId: 'APP_ID', apiKey: 'SEARCH_API_KEY'); final insightsClient = InsightsClient(appId: 'APP_ID', apiKey: 'INSIGHTS_API_KEY'); // Perform a search with click analytics enabled final searchResponse = await searchClient.search( searchMethodParams: SearchMethodParams( requests: [ SearchForHits( indexName: 'products', query: 'laptop', clickAnalytics: true, hitsPerPage: 20, ), ], ), ); // Track user interactions final hits = searchResponse.results.first.hits; final queryID = searchResponse.results.first.queryID; await insightsClient.pushEvents( insightsEvents: InsightsEvents( events: [ // User clicked on the first result InsightsEvent( eventType: 'click', eventName: 'Product Clicked', indexName: 'products', userToken: 'user-123', objectID: hits[0].objectID, position: 1, queryID: queryID, timestamp: DateTime.now().millisecondsSinceEpoch, ), // Later, user made a purchase InsightsEvent( eventType: 'conversion', eventName: 'Product Purchased', indexName: 'products', userToken: 'user-123', objectID: hits[0].objectID, value: 999.99, timestamp: DateTime.now().millisecondsSinceEpoch, ), ], ), ); } ``` -------------------------------- ### Facets Usage Example Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/types.md Demonstrates how to iterate through facet data in a search response. ```dart if (response.facets != null) { response.facets!.forEach((facetName, facetValues) { print('Facet: $facetName'); facetValues.forEach((value, count) { print(' $value: $count'); }); }); } ``` -------------------------------- ### High-Performance Algolia SearchClient Setup (Search-Heavy) Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/configuration.md This configuration is optimized for search-heavy applications, focusing on reduced timeouts for read operations and specifying multiple read hosts for performance and redundancy. It also enables gzip compression. ```dart final client = SearchClient( appId: 'YOUR_APP_ID', apiKey: 'YOUR_API_KEY', options: ClientOptions( connectTimeout: Duration(seconds: 2), readTimeout: Duration(seconds: 5), writeTimeout: Duration(seconds: 30), hosts: [ Host(url: 'cdn.algolia.net', callType: CallType.read), Host(url: 'primary.algolia.net', callType: CallType.read), Host(url: 'fallback.algolia.net'), ], compression: 'gzip', ), ); ``` -------------------------------- ### Authentication Interceptor Example Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/configuration.md An example of a custom interceptor that adds an 'Authorization' header to requests. ```dart class AuthInterceptor extends Interceptor { @override void onRequest(RequestOptions options, RequestInterceptorHandler handler) { options.headers['Authorization'] = 'Bearer ${getToken()}'; handler.next(options); } } ``` -------------------------------- ### Monorepo Structure Example Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/AGENTS.md Illustrates the monorepo structure for the Dart client, showing the organization of core transport, API clients, and the umbrella package. ```plaintext packages/ ├── client_core/ # Core transport (hand-written) ├── client_search/ # Search API client ├── client_insights/ # Insights API client ├── client_recommend/ # Recommend API client └── algoliasearch/ # Umbrella package ``` -------------------------------- ### Example of Handling AlgoliaNoResponse Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/errors.md Demonstrates how to check if a result is an AlgoliaNoResponse, indicating a successful deletion with no content returned. ```dart final result = await client.customDelete( path: '/1/indexes/products', ); if (result is AlgoliaNoResponse) { print('Delete successful, no content returned'); } ``` -------------------------------- ### Handling UnreachableHostsException Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/errors.md Example of catching and handling UnreachableHostsException, iterating through individual host errors and displaying a support message. ```dart try { await client.search( searchMethodParams: SearchMethodParams(requests: [...]), ); } on UnreachableHostsException catch (e) { print('All hosts unreachable'); print('Errors from each host:'); for (final error in e.errors) { if (error is AlgoliaApiException) { print(' - API Error ${error.statusCode}: ${error.error}'); } else if (error is AlgoliaTimeoutException) { print(' - Timeout: ${error.error}'); } else if (error is AlgoliaIOException) { print(' - I/O Error: ${error.error}'); } } print('Support: ${e.message}'); // Implement fallback or alerting } ``` -------------------------------- ### SearchResponses Usage Example Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/types.md Shows how to process the results from a multi-index search. Iterates through the list of SearchResponse objects to access results for each index. ```dart final response = await client.search( searchMethodParams: SearchMethodParams( requests: [ SearchForHits(indexName: 'products', query: 'laptop'), SearchForHits(indexName: 'articles', query: 'laptop'), ], ), ); for (int i = 0; i < response.results.length; i++) { print('Results for request $i: ${response.results[i].nbHits} hits'); } ``` -------------------------------- ### SearchResponse Usage Example Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/types.md Demonstrates how to use the SearchResponse object after a search operation. Access hit counts, processing time, and iterate through individual hits. ```dart final response = await client.searchSingleIndex( indexName: 'products', searchParams: SearchParamsObject(query: 'laptop', hitsPerPage: 20), ); print('Found ${response.nbHits} hits'); print('Processing took ${response.processingTimeMS}ms'); for (final hit in response.hits) { print('${hit.objectID}: ${hit.data}'); } if (response.queryID != null) { // Track clicks for this search print('Query ID: ${response.queryID}'); } ``` -------------------------------- ### Install Algolia Search Client for Dart Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/README.md Add the algoliasearch package to your Dart or Flutter project using the Dart or Flutter CLI. ```bash # For Dart dart pub add algoliasearch # For Flutter flutter pub add algoliasearch ``` -------------------------------- ### Add Algolia Client Core to Flutter Project Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/packages/client_core/README.md Install the Algolia Client Core package for Flutter projects using the Flutter CLI. ```shell flutter pub add algolia_client_core ``` -------------------------------- ### Hit Data Access Example Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/types.md Demonstrates how to access data from a Hit object. Retrieve the objectID, specific record attributes from the 'data' map, and check for highlighting information. ```dart final hit = response.hits.first; // Get record ID print(hit.objectID); // Access record attributes final name = hit.data['name']; final price = hit.data['price']; // Check highlighting if (hit._highlightResult != null) { final highlighted = hit._highlightResult!['name']; // Contains HTML tags: keyword } ``` -------------------------------- ### Get Index Settings Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/search-client.md Retrieves all settings for a specified index. Use this method to inspect the current configuration of an index. ```dart Future getSettings({ required String indexName, RequestOptions? requestOptions, }) ``` ```dart final settings = await client.getSettings(indexName: 'products'); print(settings.ranking); ``` -------------------------------- ### Custom Proxy Configuration for Algolia Client Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/configuration.md This example demonstrates how to configure a custom HTTP client adapter to route Algolia requests through a proxy. You need to implement the HttpClientAdapter interface with your proxy logic. ```dart class ProxyAdapter extends HttpClientAdapter { @override Future fetch( RequestOptions options, Stream? requestStream, Future Function()? cancelFuture, ) { // Add proxy configuration return super.fetch(options, requestStream, cancelFuture); } } final client = SearchClient( appId: 'YOUR_APP_ID', apiKey: 'YOUR_API_KEY', options: ClientOptions( httpClientAdapter: ProxyAdapter(), ), ); ``` -------------------------------- ### Add Algolia Client Core to Dart Project Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/packages/client_core/README.md Install the Algolia Client Core package for Dart projects using the Dart CLI. ```shell dart pub add algolia_client_core ``` -------------------------------- ### Initialize InsightsClient with Region Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/configuration.md Initialize the InsightsClient, specifying a data residency region for compliance. This example sets the region to 'de' for European data residency. ```dart final client = InsightsClient( appId: '6BE0576FF4', apiKey: 'YOUR_INSIGHTS_API_KEY', region: 'de', // EU data residency ); ``` -------------------------------- ### Error Handling with Custom Timeouts Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/request-options.md Provides an example of how to implement error handling for timeout exceptions and retry requests with a longer timeout if necessary. ```APIDOC ## Error Handling with RequestOptions Handle timeout errors when using custom timeouts: ```dart Future searchWithFallback( String indexName, String query, Duration? customTimeout, ) async { try { return await client.searchSingleIndex( indexName: indexName, searchParams: SearchParamsObject(query: query), requestOptions: RequestOptions( readTimeout: customTimeout, ), ); } on AlgoliaTimeoutException { print('Request timed out with timeout: $customTimeout'); // Retry with longer timeout if (customTimeout == null || customTimeout.inSeconds < 30) { return searchWithFallback( indexName, query, Duration(seconds: 30), ); } rethrow; } } ``` ``` -------------------------------- ### Dart Null Safety Examples Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/AGENTS.md Illustrates Dart's sound null safety features, including nullable and non-nullable types, providing defaults with `??`, and safe access with `?.`. Use `!` sparingly. ```dart // Dart has sound null safety String? nullable; // Can be null String nonNull = ''; // Cannot be null // Use ?? for defaults final value = nullable ?? 'default'; // Use ?. for safe access final length = nullable?.length; // Use ! only when certain (avoid if possible) final sure = nullable!; // Throws if null ``` -------------------------------- ### Handle AlgoliaTimeoutException Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/errors.md Provides an example of how to catch and handle AlgoliaTimeoutException during an API search request. It shows how to access the error details and suggests implementing retry logic with potentially longer timeouts. ```dart try { final response = await client.search( searchMethodParams: SearchMethodParams(requests: [...]), ).timeout(Duration(seconds: 30)); } on AlgoliaTimeoutException catch (e) { print('Request timed out: ${e.error}'); // Retry with longer timeout or use fallback } ``` -------------------------------- ### Send Custom GET Request Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/insights-client.md Sends a custom GET request to the Insights API. Use this for retrieving data via a specific API path and optional query parameters. ```dart Future customGet({ required String path, Map? parameters, RequestOptions? requestOptions, }) ``` ```dart final result = await client.customGet(path: '/1/events'); ``` -------------------------------- ### Initialize SearchClient for Production Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/README.md Configure the client for production with specific timeouts, compression, and a logger. Ensure to adjust timeout durations based on network conditions. ```dart final client = SearchClient( appId: 'APP_ID', apiKey: 'API_KEY', options: ClientOptions( connectTimeout: Duration(seconds: 5), readTimeout: Duration(seconds: 10), writeTimeout: Duration(seconds: 30), compression: 'gzip', logger: developmentLogger, ), ); ``` -------------------------------- ### Initialize SearchClient for Development Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/README.md Use this configuration for development environments. It requires only the application ID and API key. ```dart final client = SearchClient( appId: 'APP_ID', apiKey: 'API_KEY', ); ``` -------------------------------- ### Custom GET Request with Algolia Search Client Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/search-client.md Sends a custom GET request to the Algolia API. Use this for operations not covered by specific client methods. Requires a path and can include parameters. ```dart Future customGet({ required String path, Map? parameters, RequestOptions? requestOptions, }) ``` ```dart final result = await client.customGet( path: '/1/indexes/products', parameters: {'hitsPerPage': 10}, ); ``` -------------------------------- ### Standard Timeout Configuration (Recommended) Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/configuration.md The recommended preset ClientOptions for general use, balancing responsiveness and reliability. ```dart const ClientOptions( connectTimeout: Duration(seconds: 2), readTimeout: Duration(seconds: 5), writeTimeout: Duration(seconds: 30), ) ``` -------------------------------- ### Build Dart Client Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/AGENTS.md Command to build the Dart client from the repository root using the provided CLI tool. ```bash # From repo root (api-clients-automation) yarn cli build clients dart # Build Dart client ``` -------------------------------- ### Get a Single Rule Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/search-client.md Retrieves a single rule by its ID from the specified index. ```dart Future getRule({ required String indexName, required String ruleID, RequestOptions? requestOptions, }) ``` ```dart final rule = await client.getRule( indexName: 'products', ruleID: 'rule-1', ); ``` -------------------------------- ### SearchClient Constructor Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/search-client.md Initializes a new instance of the SearchClient with application credentials and optional client configurations. ```APIDOC ## SearchClient Constructor ### Description Initializes a new instance of the SearchClient with application credentials and optional client configurations. ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters - **appId** (String) - Required - Algolia application ID - **apiKey** (String) - Required - Algolia API key with appropriate permissions - **options** (ClientOptions) - Optional - HTTP client configuration including timeouts, hosts, headers, interceptors - **transformationOptions** (TransformationOptions?) - Optional - Configuration for data transformation operations; enables `*WithTransformation` helper methods ``` -------------------------------- ### Perform a Basic Search with Dart Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/README.md Initialize the SearchClient and perform a search query. Prints the number of hits and details of each hit. ```dart import 'package:algolia_client_search/algolia_client_search.dart'; void main() async { final client = SearchClient( appId: 'YOUR_APP_ID', apiKey: 'YOUR_API_KEY', ); // Search final response = await client.search( searchMethodParams: SearchMethodParams( requests: [ SearchForHits( indexName: 'products', query: 'laptop', hitsPerPage: 20, ), ], ), ); print('Found ${response.results.first.nbHits} hits'); for (final hit in response.results.first.hits) { print('${hit.objectID}: ${hit.data}'); } } ``` -------------------------------- ### Handling AlgoliaWaitException Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/errors.md Example of how to catch and handle AlgoliaWaitException, typically used when an operation fails after exhausting all retries. ```dart try { final response = await client.search( searchMethodParams: SearchMethodParams(requests: [...]), ); } on AlgoliaWaitException catch (e) { print('Wait/retry error: ${e.error}'); // All retries exhausted, operation failed } ``` -------------------------------- ### Initialize Search Client and Save Object Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/README.md Import the Algolia client, initialize the SearchClient with your App ID and API Key, and save a new record to your Algolia index. Use waitTask to ensure the object is indexed. ```dart import 'package:algolia_client_search/algolia_client_search.dart'; // Alternatively, you can import `algoliasearch_lite`, a **search-only** version of the library, if you do not need the full feature set: // import 'package:algoliasearch/algoliasearch_lite.dart'; final client = SearchClient(appId: 'YOUR_APP_ID', apiKey: 'YOUR_API_KEY'); // Add a new record to your Algolia index final response = await client.saveObject( indexName: "", body: { 'objectID': "id", 'test': "val", }, ); // Poll the task status to know when it has been indexed await client.waitTask('', response.taskID); ``` -------------------------------- ### Get a Single Synonym Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/search-client.md Retrieves a single synonym from an index by its unique identifier. Returns the synonym data. ```dart Future getSynonym({ required String indexName, required String synonymID, RequestOptions? requestOptions, }) ``` ```dart final synonym = await client.getSynonym( indexName: 'products', synonymID: 'syn-1', ); ``` -------------------------------- ### Algolia Search Client Package Structure Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/README.md Overview of the directory structure for the `algolia_client_search` package, highlighting key files and subdirectories. ```plaintext algolia_client_search/ ├── lib/ │ ├── algolia_client_search.dart (Main export) │ └── src/ │ ├── api/ │ │ └── search_client.dart (SearchClient class) │ ├── model/ (100+ type definitions) │ └── extension.dart ├── pubspec.yaml └── README.md algolia_client_insights/ ├── lib/ │ ├── algolia_client_insights.dart (Main export) │ └── src/ │ ├── api/ │ │ └── insights_client.dart (InsightsClient class) │ └── model/ └── pubspec.yaml algolia_client_core/ ├── lib/ │ ├── algolia_client_core.dart (Main export) │ └── src/ │ ├── algolia_exception.dart (Exception types) │ ├── api_client.dart │ ├── config/ │ │ ├── client_options.dart │ │ ├── host.dart │ │ └── ... │ └── transport/ │ ├── retry_strategy.dart │ ├── request_options.dart │ └── requester.dart └── pubspec.yaml ``` -------------------------------- ### customGet Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/insights-client.md Sends a custom GET request to the Insights API. Allows for flexible querying of API endpoints. ```APIDOC ## GET /{path} ### Description Sends a custom GET request to the Insights API. Allows for flexible querying of API endpoints. ### Method GET ### Endpoint /{path} ### Parameters #### Path Parameters - **path** (String) - Required - API path, e.g., `1/insights` #### Query Parameters - **parameters** (Map) - Optional - Query parameters #### Request Body None ### Request Example ```json { "path": "/1/events" } ``` ### Response #### Success Response (200) - **response** (Object) - Raw API response #### Response Example ```json { "response": { ... } } ``` ``` -------------------------------- ### getSettings Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/search-client.md Retrieves all settings for a specified index. ```APIDOC ## getSettings ### Description Retrieves all settings for an index. ### Method GET ### Endpoint `/{indexName}/settings` (This is an inferred endpoint based on common REST practices for index settings, the source does not explicitly provide the HTTP endpoint) ### Parameters #### Path Parameters - **indexName** (string) - Required - The name of the index. #### Query Parameters None explicitly documented. #### Request Body None explicitly documented. ### Request Example ```dart final settings = await client.getSettings(indexName: 'products'); print(settings.ranking); ``` ### Response #### Success Response (200) - **SettingsResponse** - Complete index settings ``` -------------------------------- ### Initialize SearchClient with Custom Options Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/configuration.md Use this to initialize the SearchClient with specific HTTP client configurations like connection and read timeouts. Ensure you have your Algolia application ID and API key. ```dart final client = SearchClient( appId: '6BE0576FF4', apiKey: 'YOUR_SEARCH_API_KEY', options: ClientOptions( connectTimeout: Duration(seconds: 5), readTimeout: Duration(seconds: 10), ), ); ``` -------------------------------- ### Import Algolia Search-only Client Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/README.md Import this for a client focused solely on search capabilities. ```dart // Search only import 'package:algolia_client_search/algolia_client_search.dart'; ``` -------------------------------- ### ClientOptions Configuration Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/INDEX.md Configure global settings for the Algolia client, including timeouts, hosts, headers, and more. ```APIDOC ## Client Configuration Options ### Description Set global configurations for the Algolia client. ### Options - `connectTimeout` (Duration) - Connection timeout duration. - `readTimeout` (Duration) - Read timeout duration. - `writeTimeout` (Duration) - Write timeout duration. - `hosts` (List) - Custom endpoints and failover hosts. - `headers` (Map) - Default headers for all requests. - `interceptors` (List) - Request and response interceptors. - `useGzip` (bool) - Enable or disable gzip compression. - `logger` (Function?) - Custom logger function for debugging. ``` -------------------------------- ### customGet Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/search-client.md Sends a custom GET request to the Algolia API. Allows for specifying the path, query parameters, and request options. ```APIDOC ## customGet ### Description Sends a custom GET request to the Algolia API. Allows for specifying the path, query parameters, and request options. ### Method GET ### Endpoint /{path} ### Parameters #### Path Parameters - **path** (string) - Required - The API path to send the GET request to. #### Query Parameters - **parameters** (Map) - Optional - A map of query parameters to include in the request. #### Request Body This method does not support a request body. ### Response #### Success Response (200) - **Object** - Raw API response. ### Request Example ```dart final result = await client.customGet( path: '/1/indexes/products', parameters: {'hitsPerPage': 10}, ); ``` ``` -------------------------------- ### Import Algolia Search Only Client (Full) Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/INDEX.md Import this for a comprehensive search-only client, excluding insights functionality. ```dart import 'package:algolia_client_search/algolia_client_search.dart'; ``` -------------------------------- ### Handling Algolia API Errors Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/errors.md Example of how to catch and handle AlgoliaApiException, checking specific status codes for different error scenarios. ```dart import 'package:algolia_client_search/algolia_client_search.dart'; try { await client.saveObject( indexName: 'products', body: {'name': 'item'}, ); } on AlgoliaApiException catch (e) { if (e.statusCode == 400) { print('Bad request: ${e.error}'); } else if (e.statusCode == 401) { print('Invalid API key'); } else if (e.statusCode == 429) { print('Rate limited, retry after delay'); } else if (e.statusCode >= 500) { print('Server error, will retry'); } } ``` -------------------------------- ### Import Algolia Core Utilities Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/README.md Import this for core utilities that might be shared across different Algolia client modules. ```dart // Core utilities import 'package:algolia_client_core/algolia_client_core.dart'; ``` -------------------------------- ### Configure SearchClient with Environment Variables (Dart CLI/VM) Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/configuration.md Initialize the SearchClient using environment variables for application ID and API key. This is suitable for Dart CLI or VM applications. Ensure variables are passed during runtime. ```dart void main() { const appId = String.fromEnvironment('ALGOLIA_APP_ID'); const apiKey = String.fromEnvironment('ALGOLIA_API_KEY'); final client = SearchClient(appId: appId, apiKey: apiKey); } // Run with: dart run --define=ALGOLIA_APP_ID=... --define=ALGOLIA_API_KEY=... ``` -------------------------------- ### Configure SearchClient with Environment Variables (Flutter) Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/configuration.md Initialize the SearchClient using environment variables loaded from a .env file for Flutter applications. Requires the flutter_dotenv package. Ensure the .env file is present in the project root. ```dart import 'package:flutter_dotenv/flutter_dotenv.dart'; void main() async { await dotenv.load(); final appId = dotenv.env['ALGOLIA_APP_ID']!; final apiKey = dotenv.env['ALGOLIA_API_KEY']!; final client = SearchClient(appId: appId, apiKey: apiKey); runApp(MyApp(client: client)); } ``` ```dotenv ALGOLIA_APP_ID=6BE0576FF4 ALGOLIA_API_KEY=YOUR_SEARCH_API_KEY ``` -------------------------------- ### EU Data Residency with Compression Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/client-options.md Configure the client for EU data residency by specifying EU hosts and setting the 'X-Data-Residency' header. Compression is also enabled using 'gzip'. ```dart final options = ClientOptions( hosts: [ Host(url: 'algolia.eu-central-1.algolia.net'), Host(url: 'algolia-eu-fallback.algolia.net'), ], compression: 'gzip', headers: { 'X-Data-Residency': 'eu', }, ); final client = SearchClient( appId: 'APP_ID', apiKey: 'API_KEY', options: options, ); ``` -------------------------------- ### Get Application Task Status Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/search-client.md Retrieves the status of a global, application-level task. This is useful for monitoring tasks that affect the entire Algolia application. ```dart Future getAppTask({ required int taskID, RequestOptions? requestOptions, }) ``` ```dart final status = await client.getAppTask(taskID: 456789); ``` -------------------------------- ### ClientOptions Constructor Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/client-options.md The ClientOptions class allows customization of the HTTP client used by Algolia clients. You can configure various aspects like connection and read/write timeouts, custom hosts, default headers, and more. ```APIDOC ## ClientOptions Constructor ### Description Allows customization of HTTP client behavior for Algolia clients. ### Parameters - **connectTimeout** (Duration) - Optional - The maximum duration to wait for a TCP connection to establish before timing out. Defaults to `ClientOptions.unsetTimeout` (uses per-client default: 2 seconds). - **writeTimeout** (Duration) - Optional - The maximum duration to wait for a write operation to complete before timing out. Defaults to `ClientOptions.unsetTimeout` (uses per-client default: 30 seconds). - **readTimeout** (Duration) - Optional - The maximum duration to wait for a read operation to complete before timing out. Defaults to `ClientOptions.unsetTimeout` (uses per-client default: 5 seconds). - **hosts** (Iterable?) - Optional - List of hosts (endpoints) to connect to, with optional routing by call type (read/write). Defaults to `null` (uses client-specific defaults). - **headers** (Map?) - Optional - Default HTTP headers to include in every request. Defaults to `null`. - **agentSegments** (Iterable?) - Optional - List of agent segments to include in the User-Agent header for tracking SDK usage. Defaults to `null`. - **logger** (Function(Object?)?) - Optional - A function to log client activity. - **requester** (Requester?) - Optional - A custom requester implementation. - **interceptors** (Iterable?) - Optional - A list of interceptors to apply to requests. - **httpClientAdapter** (HttpClientAdapter?) - Optional - A custom HTTP client adapter. - **compression** (String?) - Optional - Specifies the compression method to use for requests. ``` -------------------------------- ### Get Task Status Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/search-client.md Retrieves the status of an indexing task using the index name and task ID. Use this to check if an operation has completed. ```dart Future getTask({ required String indexName, required int taskID, RequestOptions? requestOptions, }) ``` ```dart final status = await client.getTask( indexName: 'products', taskID: 123456, ); if (status.status == 'published') { print('Task completed'); } ``` -------------------------------- ### Async/Await Usage in API Methods Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/AGENTS.md Demonstrates the use of `async/await` for API calls, showing both direct usage and the `.then()` alternative for handling asynchronous responses. ```dart // All API methods are async Future search(SearchParams params); // Usage final response = await client.search(params); // Or with then client.search(params).then((response) { // handle response }); ``` -------------------------------- ### Initialize SearchClient Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/search-client.md Instantiate the SearchClient with your Algolia application ID and API key. Optional parameters allow for custom HTTP client configurations and data transformation settings. ```dart final client = SearchClient(appId: 'APP_ID', apiKey: 'API_KEY'); ``` -------------------------------- ### Import Full-featured Algolia Client Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/README.md Use this import for the full-featured client that includes both search and insights functionalities. ```dart // Full-featured (search + insights) import 'package:algoliasearch/algoliasearch.dart'; ``` -------------------------------- ### Request and Response Interceptors with Logging Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/client-options.md Integrate custom interceptors, such as a logging interceptor, to observe and modify requests and responses. This example uses Dio's Interceptor. ```dart import 'package:dio/dio.dart'; class LoggingInterceptor extends Interceptor { @override void onRequest(RequestOptions options, RequestInterceptorHandler handler) { print('➜ ${options.method} ${options.path}'); handler.next(options); } @override void onResponse(Response response, ResponseInterceptorHandler handler) { print('✓ ${response.statusCode} ${response.requestOptions.path}'); handler.next(response); } @override void onError(DioException err, ErrorInterceptorHandler handler) { print('✗ ${err.message}'); handler.next(err); } } final options = ClientOptions( interceptors: [LoggingInterceptor()], logger: print, ); ``` -------------------------------- ### ClientOptions Constructor Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/configuration.md The main constructor for ClientOptions, accepting various parameters to configure HTTP behavior. ```dart const ClientOptions({ Duration connectTimeout = unsetTimeout, Duration writeTimeout = unsetTimeout, Duration readTimeout = unsetTimeout, Iterable? hosts, Map? headers, Iterable? agentSegments, Function(Object?)? logger, Requester? requester, Iterable? interceptors, HttpClientAdapter? httpClientAdapter, String? compression, }) ``` -------------------------------- ### Error Handling with Custom Timeouts Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/request-options.md Implement a retry mechanism for requests that time out, by first attempting with a custom timeout and then retrying with a longer duration if necessary. This example specifically handles `AlgoliaTimeoutException`. ```dart Future searchWithFallback( String indexName, String query, Duration? customTimeout, ) async { try { return await client.searchSingleIndex( indexName: indexName, searchParams: SearchParamsObject(query: query), requestOptions: RequestOptions( readTimeout: customTimeout, ), ); } on AlgoliaTimeoutException { print('Request timed out with timeout: $customTimeout'); // Retry with longer timeout if (customTimeout == null || customTimeout.inSeconds < 30) { return searchWithFallback( indexName, query, Duration(seconds: 30), ); } rethrow; } } ``` -------------------------------- ### Constructor for RequestOptions Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/request-options.md Initializes RequestOptions with optional connection, read, write timeouts, headers, and body. ```dart const RequestOptions({ Duration? connectTimeout, Duration? readTimeout, Duration? writeTimeout, Map? headers, Object? body, }) ``` -------------------------------- ### Import Full algoliasearch Package Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/packages/algoliasearch/README.md Import the main algoliasearch package to use all its features, including indexing, search, and personalization. ```dart import 'package:algoliasearch/algoliasearch.dart'; ``` -------------------------------- ### Perform Algolia Search with Typo Tolerance Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/README.md Fetch search results from your Algolia index, specifying the index name, query, and number of hits per page. This example demonstrates basic search functionality with typo tolerance enabled by default. ```dart final response = await client.search( searchMethodParams: SearchMethodParams( requests: [ SearchForHits( indexName: "", query: "", hitsPerPage: 50, ), ], ), ); ``` -------------------------------- ### Import Algolia Search-only Lite Client Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/README.md This import provides a lite variant of the search-only client, potentially for reduced dependencies or size. ```dart // Search only (lite variant) import 'package:algoliasearch/algoliasearch_lite.dart'; ``` -------------------------------- ### Basic Search Client with Custom Timeouts Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/client-options.md Configure a SearchClient with custom connection, read, and write timeouts. Ensure to replace placeholder values for appId and apiKey. ```dart import 'package:algolia_client_search/algolia_client_search.dart'; import 'package:algolia_client_core/algolia_client_core.dart'; void main() { final client = SearchClient( appId: 'YOUR_APP_ID', apiKey: 'YOUR_API_KEY', options: ClientOptions( connectTimeout: Duration(seconds: 3), readTimeout: Duration(seconds: 10), writeTimeout: Duration(seconds: 60), ), ); } ``` -------------------------------- ### Package Import Convention Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/AGENTS.md Demonstrates the correct way to import packages in Dart, emphasizing importing from the package name rather than relative paths for external dependencies. ```dart // Import from package, not relative paths import 'package:algoliasearch/algoliasearch.dart'; // For internal imports in same package import 'src/model/search_params.dart'; ``` -------------------------------- ### Verify Correct Repository Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/AGENTS.md Before making any changes, ensure you are in the correct repository to avoid unintended modifications to the public repository. ```bash git remote -v ``` -------------------------------- ### Instantiate InsightsClient Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/insights-client.md Initialize the InsightsClient with your Algolia application ID and API key. Optionally, specify a data residency region for compliance. ```dart InsightsClient({ required String appId, required String apiKey, ClientOptions options = const ClientOptions(), String? region, }) ``` -------------------------------- ### Initialize SearchClient and InsightsClient for GDPR Compliance (EU) Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/README.md Configure clients to comply with GDPR by specifying the EU region for the search client and a specific region for the insights client. This ensures data is processed within the designated geographical boundaries. ```dart final searchClient = SearchClient( appId: 'APP_ID', apiKey: 'API_KEY', options: ClientOptions( hosts: [Host(url: 'algolia.eu-west-1.algolia.net')], ), ); final insightsClient = InsightsClient( appId: 'APP_ID', apiKey: 'API_KEY', region: 'de', ); ``` -------------------------------- ### Add Algolia Recommend API Client to Flutter Project Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/packages/client_recommend/README.md Use this command to add the Algolia Recommend API Client as a dependency in your Flutter projects. ```shell flutter pub add algolia_client_recommend ``` -------------------------------- ### Configure Custom Hosts Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/client-options.md Specify a list of hosts to connect to, with optional routing by call type. Hosts are tried in order until one succeeds. ```dart final options = ClientOptions( hosts: [ Host(url: 'algolia-us.example.com', callType: CallType.read), Host(url: 'algolia-eu.example.com', callType: CallType.write), Host(url: 'algolia-fallback.example.com'), ], ); ``` -------------------------------- ### Configure Client Timeouts Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/errors.md Demonstrates how to configure custom timeout durations for client connections, reads, and writes using ClientOptions. This is useful for adjusting request timing based on network conditions or API behavior. ```dart final options = ClientOptions( connectTimeout: Duration(seconds: 5), readTimeout: Duration(seconds: 10), writeTimeout: Duration(seconds: 60), ); final client = SearchClient( appId: 'APP_ID', apiKey: 'API_KEY', options: options, ); ``` -------------------------------- ### Import algoliasearch Lite Package Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/packages/algoliasearch/README.md Import the algoliasearch_lite package for a search-only version of the library, suitable for projects that do not require full feature set. ```dart import 'package:algoliasearch/algoliasearch_lite.dart'; ``` -------------------------------- ### Overriding Client Options with Request Options Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/request-options.md Demonstrates how to set default client-wide options and then override specific options like readTimeout for individual requests. ```APIDOC ## Combining with ClientOptions Request options override client options: ```dart // Client-level configuration final client = SearchClient( appId: 'APP_ID', apiKey: 'API_KEY', options: ClientOptions( readTimeout: Duration(seconds: 5), // Default ), ); // Request-level override await client.search( searchMethodParams: params, requestOptions: RequestOptions( readTimeout: Duration(seconds: 20), // This request uses 20s ), ); // Other requests still use 5s from ClientOptions ``` ``` -------------------------------- ### InsightsClient Constructor Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/insights-client.md Initializes the InsightsClient with Algolia application credentials and optional configurations for HTTP client and data residency region. ```APIDOC ## Constructor InsightsClient ### Description Initializes the InsightsClient with Algolia application credentials and optional configurations for HTTP client and data residency region. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **appId** (String) - Required - Algolia application ID - **apiKey** (String) - Required - Algolia API key with insights permissions - **options** (ClientOptions) - Optional - HTTP client configuration - **region** (String?) - Optional - Data residency region: 'de' (Germany) or 'us' (United States); defaults to global insights.algolia.io ``` -------------------------------- ### Add Algolia Recommend API Client to Dart Project Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/packages/client_recommend/README.md Use this command to add the Algolia Recommend API Client as a dependency in your Dart projects. ```shell dart pub add algolia_client_recommend ``` -------------------------------- ### Basic Logging Configuration Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/configuration.md Configures a simple logger function to print network-related messages to the console. ```dart logger: (message) { print('[Algolia] $message'); } ``` -------------------------------- ### Import Algolia Core Client Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/INDEX.md This import is for the core functionalities, including exceptions and configuration, which may be used independently or with other clients. ```dart import 'package:algolia_client_core/algolia_client_core.dart'; ``` -------------------------------- ### JSON Serialization with json_serializable Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/AGENTS.md Shows how models utilize the `json_serializable` package for JSON serialization and deserialization, including custom key mapping. ```dart // Models use json_serializable @JsonSerializable() class SearchParams { final String query; @JsonKey(name: 'hitsPerPage') final int? hitsPerPage; factory SearchParams.fromJson(Map json) => _$SearchParamsFromJson(json); } ``` -------------------------------- ### addApiKey Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/search-client.md Creates a new API key with specific permissions. Requires 'admin' ACLs. ```APIDOC ## addApiKey ### Description Creates a new API key with specific permissions. ### Method Signature ```dart Future addApiKey({ required ApiKey apiKey, RequestOptions? requestOptions, }) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **apiKey** (ApiKey) - Required - API key configuration with ACLs and restrictions - **requestOptions** (RequestOptions?) - Optional - Additional request options ### Request Example ```dart final response = await client.addApiKey( apiKey: ApiKey( acl: ['search', 'addObject'], validity: 3600, ), ); print('Key: ${response.key}'); ``` ### Response #### Success Response (`Future`) - Response with generated key ### Required API Key ACLs - `admin` ``` -------------------------------- ### Fast Mobile Timeout Configuration Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/configuration.md Preset ClientOptions for fast mobile connections with low bandwidth, optimizing for quicker responses. ```dart const ClientOptions( connectTimeout: Duration(seconds: 3), readTimeout: Duration(seconds: 5), writeTimeout: Duration(seconds: 15), ) ``` -------------------------------- ### Custom Hosts with Fallback Strategy Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/client-options.md Configure custom hosts for read and write operations, including fallback hosts. This is useful for directing traffic to specific regions or for redundancy. ```dart final options = ClientOptions( hosts: [ Host(url: 'primary-algolia.example.com', callType: CallType.read), Host(url: 'primary-algolia.example.com', callType: CallType.write), Host(url: 'fallback-algolia.example.com'), Host(url: 'final-fallback-algolia.example.com'), ], ); final client = SearchClient( appId: 'APP_ID', apiKey: 'API_KEY', options: options, ); ``` -------------------------------- ### Custom HTTP Client Adapter with HTTP/2 Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/client-options.md Configure a custom HTTP client adapter, such as the HTTP/2 adapter, for advanced networking control. This allows for features like custom connection management and response timeouts. ```dart import 'package:dio/dio.dart'; import 'package:dio_http2_adapter/dio_http2_adapter.dart'; final options = ClientOptions( httpClientAdapter: Http2Adapter( ConnectionManager( idleTimeout: Duration(seconds: 4), responseTimeout: Duration(seconds: 4), ), ), ); ``` -------------------------------- ### Configure TransformationOptions for SearchClient Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/configuration.md Set transformation options when initializing the SearchClient for bulk operations. Supports specifying a region and custom HTTP client options for ingestion. ```dart final client = SearchClient( appId: 'APP_ID', apiKey: 'API_KEY', transformationOptions: TransformationOptions( region: 'us', // or 'de' ingestionClientOptions: ClientOptions( connectTimeout: Duration(seconds: 5), ), ), ); ``` -------------------------------- ### httpClientAdapter Source: https://github.com/algolia/algoliasearch-client-dart/blob/main/_autodocs/api-reference/client-options.md Custom HTTP client adapter for Dio, allowing advanced configuration of the underlying HTTP transport. Only used with the default Dio requester. ```APIDOC ## httpClientAdapter ### Description Custom HTTP client adapter (Dio-specific, advanced). ### Type `HttpClientAdapter?` ### Default `null` (uses Dio default adapter) ### Notes - Only used with default Dio requester - Allows replacing the underlying HTTP transport - Useful for custom certificate validation or proxy configuration ### Example ```dart import 'package:dio/dio.dart'; import 'package:dio_http2_adapter/dio_http2_adapter.dart'; final options = ClientOptions( httpClientAdapter: Http2Adapter( ConnectionManager( idleTimeout: Duration(seconds: 4), responseTimeout: Duration(seconds: 4), ), ), ); ``` ```