Customized client usage
You might want to customize how the API client works, by providing additional information to your request, adding user-agents or use your own HTTP requester.
Setting a logger
You can set a custom logger on the client to enable more or less debug output depending on your need.
- C#
- Dart
- Go
- Java
- JavaScript
- Kotlin
- PHP
- Python
- Ruby
- Scala
- Swift
import com.algolia.api.SearchClient;
import com.algolia.config.ClientOptions;
ClientOptions options = ClientOptions.builder()
.setLogger(message -> System.out.println(message))
.build();
SearchClient client = new SearchClient(
"<YOUR_INDEX_NAME>",
"<YOUR_API_KEY>",
options
);
import com.algolia.client.api.SearchClient
import com.algolia.client.configuration.ClientOptions
import io.ktor.client.plugins.logging.Logger
val client = SearchClient(
appId = "<YOUR_INDEX_NAME>",
apiKey = "<YOUR_API_KEY>",
options = ClientOptions(
logger = object : Logger {
override fun log(message: String) {
println(message)
}
},
)
)
var client = SearchClient(
appId: '<YOUR_INDEX_NAME>',
apiKey: '<YOUR_API_KEY>',
options: ClientOptions(logger: print),
);
If you enable the debug
property of the Go API client, it will print the request and response to the standard output.
searchClient, _ := search.NewClientWithConfig(search.Configuration{
AppID: "<YOUR_APP_ID>",
ApiKey: "<YOUR_API_KEY>",
Debug: true,
})
using Algolia.Search.Clients;
using Microsoft.Extensions.Logging;
var loggerFactory = LoggerFactory.Create(builder =>
{
// Log everything from Algolia in the console, including debug logs
builder.AddFilter("Algolia", LogLevel.Debug).AddConsole();
});
var client = new SearchClient("<YOUR_APP_ID>", "<YOUR_API_KEY>", loggerFactory);
Send additional information in your request with requestOptions
The requestOptions
parameter allows you to merge additional information with the client transporter, such as headers
or query parameters
.
Note: requestOptions
overrides the default parameters that were previously set in the method and client.
- C#
- Dart
- Go
- Java
- JavaScript
- Kotlin
- PHP
- Python
- Ruby
- Scala
- Swift
await client.search(
{
requests: [
{
indexName: '<YOUR_INDEX_NAME>',
query: '<YOUR_QUERY>',
hitsPerPage: 50,
},
],
},
{
// This header is added to the request
headers: {
'additional-header': 'hello',
},
// As we re-define `hitsPerPage`, it will override the value defined in the method's parameters.
queryParameters: {
hitsPerPage: 100,
},
}
);
$client->search(
[
'requests' => [
[
'indexName' => '<YOUR_INDEX_NAME>',
'query' => '<YOUR_QUERY>',
'hitsPerPage' => 50,
],
]
],
[
// This header is added to the request
'headers' => ['additional-header' => 'hello'],
// As we re-define `hitsPerPage`, it will override the value defined in the method's parameters.
'queryParameters' => ['hitsPerPage' => 100],
]
);
import com.algolia.model.search.*;
import com.algolia.utils.RequestOptions;
client.search(
new SearchMethodParams()
.addRequests(
new SearchForHits()
.setIndexName("<YOUR_INDEX_NAME>")
.setQuery("<YOUR_QUERY>")
.setHitsPerPage(50)
),
new RequestOptions()
// This header is added to the request
.addExtraHeader("additional-header", "hello")
// As we re-define `hitsPerPage`, it will override the value defined in the method's parameters.
.addExtraQueryParameters("hitsPerPage", 100)
);
client.search(
searchMethodParams = SearchMethodParams(
requests = listOf(
SearchForHits(
indexName = "<YOUR_INDEX_NAME>",
query = "<YOUR_QUERY>",
hitsPerPage = 50,
)
)
),
requestOptions = RequestOptions(
// This header is added to the request
headers = mapOf("additional-header" to "hello"),
// As we re-define `hitsPerPage`, it will override the value defined in the method's parameters.
urlParameters = mapOf("hitsPerPage" to 100)
)
)
await client.search(
searchMethodParams: SearchMethodParams(
requests: [
SearchForHits(
indexName: '<YOUR_INDEX_NAME>',
query: '<YOUR_QUERY>',
hitsPerPage: 50,
)
],
),
requestOptions: RequestOptions(
// This header is added to the request
headers: {'additional-header': 'hello'},
// As we re-define `hitsPerPage`, it will override the value defined in the method's parameters.
urlParameters: {'hitsPerPage': 100},
),
);
import (
"github.com/algolia/algoliasearch-client-go/v4/algolia/search"
)
indexName := "<INDEX_NAME>"
appID := "<APPLICATION_ID>"
apiKey := "<API_KEY>"
searchClient, _ := search.NewClient(appID, apiKey)
searchClient.Search(
searchClient.NewApiSearchRequest(
search.NewSearchMethodParams([]search.SearchQuery{
search.SearchForHitsAsSearchQuery(
search.NewSearchForHits(
indexName,
search.WithSearchForHitsQuery("jeans"),
search.WithSearchForHitsHitsPerPage(50),
),
),
}),
),
// This header is added to the request
search.HeaderParamOption("additional-header", "hello"),
// As we re-define `hitsPerPage`, it will override the value defined in the method's parameters.
search.QueryParamOption("hitsPerPage", 100),
)
using Algolia.Search.Clients;
using Algolia.Search.Http;
using Algolia.Search.Models.Search;
var client = new SearchClient("<YOUR_APP_ID>", "<YOUR_API_KEY>");
client.SearchSingleIndex<Hit>("<YOUR_INDEX_NAME>",
new SearchParams(new SearchParamsObject { Query = "<YOUR_QUERY>", HitsPerPage = 50 }),
// You can use the fluent builder to add extra headers, query parameters, and set the timeout.
new RequestOptionBuilder()
// This header is added to the request
.AddExtraHeader("additional-header", "hello")
.AddExtraHeader("another-header", "hello again")
// As we re-define `hitsPerPage`, it will override the value defined in the method's parameters.
.AddExtraQueryParameters("hitsPerPage", 100)
.SetTimeout(TimeSpan.FromMinutes(1)).Build());
client.SearchSingleIndex<Hit>("<YOUR_INDEX_NAME>",
new SearchParams(new SearchParamsObject { Query = "<YOUR_QUERY>", HitsPerPage = 50 }),
// You can also directly instantiate the RequestOptions object
new RequestOptions
{
Headers = new Dictionary<string, string> { { "additional-header", "hello" } },
QueryParameters = new Dictionary<string, object> { { "hitsPerPage", 100 } }
});
Provide your own user-agent
The API clients offers a method for you to append data to the current user-agent.
- C#
- Dart
- Go
- Java
- JavaScript
- Kotlin
- PHP
- Python
- Ruby
- Scala
- Swift
In the JavaScript client, user-agent are sent in the header via the
x-algolia-agent
property.
import { searchClient } from '@algolia/client-search';
const client = searchClient('<YOUR_APP_ID>', '<YOUR_API_KEY>');
// This will append `; my user agent (optional version)` to the current value of `x-algolia-agent` for every requests
client.addAlgoliaAgent('my user agent', 'optional version');
$client = SearchClient::create(
'<YOUR_APP_ID>',
'<YOUR_APP_ID>'
);
// This will append `; my user agent (optional version)` to the current value of `User-Agent` for every requests
Algolia\AlgoliaSearch\Support\AlgoliaAgent::addAlgoliaAgent(
$client->getClientConfig()->getClientName(),
"my user agent",
"optional version"
);
import com.algolia.api.SearchClient;
import com.algolia.config.ClientOptions;
// This will append `; my user agent (optional version)` to the current value of `x-algolia-agent` for every requests
ClientOptions options = ClientOptions.builder()
.addAlgoliaAgentSegment("my user agent", "optional version")
.build();
SearchClient client = new SearchClient(
"<YOUR_INDEX_NAME>",
"<YOUR_API_KEY>",
options
);
val client = SearchClient(
"<YOUR_APP_ID>",
"<YOUR_API_KEY>",
ClientOptions(
algoliaAgentSegments = listOf(
AgentSegment(
value = "my user agent",
version = "optional version",
)
)
)
)
var client = SearchClient(
appId: 'YOUR_APP_ID>',
apiKey: '<YOUR_API_KEY>',
options: ClientOptions(agentSegments: [
AgentSegment(
value: 'my user agent',
version: 'optional version',
)
]),
);
In the Go client, you can use the NewClientWithConfig method to create a new API client with the given configuration to fully customize the client behaviour. Only the AppID and APIKey are required, other configuration parameters will be defaulted if not provided.
import (
"github.com/algolia/algoliasearch-client-go/v4/algolia/search"
)
searchClient, _ := search.NewClientWithConfig(search.Configuration{
AppID: appID,
ApiKey: apiKey,
Hosts: nil,
DefaultHeader: nil,
UserAgent: "my user agent (optional version)",
Debug: false,
Requester: nil,
ReadTimeout: 0,
WriteTimeout: 0,
Compression: 0,
})
using Algolia.Search.Clients;
var searchConfig = new SearchConfig("<YOUR_APP_ID>", "<YOUR_API_KEY>");
// This will append `; my user agent (optional version)` to the current value of `x-algolia-agent` for every requests
searchConfig.UserAgent.AddSegment("my user agent", "optional version");
var client = new SearchClient(searchConfig);
Use your own HTTP requester
You can override the default requester behavior by providing your requester logic at the initialization of the client.
- C#
- Dart
- Go
- Java
- JavaScript
- Kotlin
- PHP
- Python
- Ruby
- Scala
- Swift
The JavaScript client provides an
echoRequester
, that will return the full payload of the request.
import { searchClient } from '@algolia/client-search';
import { echoRequester } from '@algolia/requester-node-http';
const client = searchClient('<YOUR_APP_ID>', '<YOUR_API_KEY>', {
// The first parameter is the status to return
requester: echoRequester(200),
});
In PHP, the requests are handled by the HTTP Client (by default GuzzleHttpClient)
use Algolia\AlgoliaSearch\Api\SearchClient;
use Algolia\AlgoliaSearch\Configuration\SearchConfig;
use Algolia\AlgoliaSearch\Http\HttpClientInterface;
use Algolia\AlgoliaSearch\RetryStrategy\ApiWrapper;
use Algolia\AlgoliaSearch\RetryStrategy\ClusterHosts;
// Create a config and a clusterhosts objects with your credentials
$config = SearchConfig::create('<YOUR_APP_ID>', '<YOUR_API_KEY>');
$clusterHosts = ClusterHosts::createFromAppId('<YOUR_APP_ID>');
// Instanciate a MyHttpClient object implementing HttpClientInterface (replacing GuzzleHttpClient)
$myHttpClient = new MyHttpClient(...);
// Now create you custom Api wrapper
$apiWrapper = new ApiWrapper($myHttpClient, $config, $clusterHosts);
// Instanciate your client using the constructor
$client = new SearchClient($apiWrapper, $config);
Create your own requester by creating a class that implements
com.algolia.utils.Requester
, and use it by passing it to the client constructor.
import com.algolia.api.SearchClient;
SearchClient client = new SearchClient(
"<YOUR_APP_ID>",
"<YOUR_API_KEY>",
ClientOptions.builder().setRequester(new MyOwnRequester()).build()
);
val client = SearchClient(
"<YOUR_APP_ID>",
"<YOUR_API_KEY>",
ClientOptions(
requester = MyOwnRequester()
)
)
var client = SearchClient(
appId: "<YOUR_APP_ID>",
apiKey: "<YOUR_API_KEY>",
options: ClientOptions(requester : MyOwnRequester())
);
In the Go client, you can use the NewClientWithConfig method to create a new API client with the given configuration to fully customize the client behaviour. Only the AppID and APIKey are required, other configuration parameters will be defaulted if not provided.
import (
"net/http"
"github.com/algolia/algoliasearch-client-go/v4/algolia/search"
)
type MyCustomRequester struct {
client *http.Client
}
func NewCustomRequester() *MyCustomRequester {
return &MyCustomRequester{
client: http.DefaultClient,
}
}
func (r *MyCustomRequester) Request(req *http.Request) (*http.Response, error) {
println("MyCustomRequester > Request: ", req.RequestURI)
return r.client.Do(req)
}
searchClient, _ := search.NewClientWithConfig(search.Configuration{
AppID: appID,
ApiKey: apiKey,
Hosts: nil,
DefaultHeader: nil,
UserAgent: "",
Debug: false,
Requester: NewCustomerRequester(),
ReadTimeout: 0,
WriteTimeout: 0,
Compression: 0,
})
Create your own requester by creating a class that implements
IHttpRequester
, and use it by passing it to the client constructor.
using Algolia.Search.Clients;
var config = new SearchConfig("<YOUR_APP_ID>", "<YOUR_API_KEY>");
var client = new SearchClient(config, new MyOwnRequester());