Swift API clients
The Swift API clients let you interact with Algolia’s APIs from your Swift backend.
Install the library
All API clients are part of the algoliasearch-client-swift
package,
which you can add to your Package.swift
file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
let package = Package(
// ...
dependencies: [
.package(url: "https://github.com/algolia/algoliasearch-client-swift.git", from: "9.7.1")
],
targets: [
.target(
// ...
dependencies: [
.product(name: "Search", package: "algoliasearch-client-swift")
]
)
]
)
Test your installation
To test your installation,
create a new Swift project, for example, with swift package init --type executable
and run a short program that adds a record to a test index,
searches your index, and prints the results.
-
If you haven’t already, create an Algolia account.
-
Copy the following code into the
Sources/main.swift
. ReplaceALGOLIA_APPLICATION_ID
andALGOLIA_API_KEY
with values from your account. Make sure to use an API key withaddObject
andsearch
permissions.Copy1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
// File: main.swift import Search let appID = "ALGOLIA_APPLICATION_ID" // API key with `addObject` and `search` ACL let apiKey = "ALGOLIA_API_KEY" let indexName = "test-index" let client = try SearchClient(appID: appID, apiKey: apiKey) // Create a new record let record = ["objectID": "object-1", "name": "test-record"] // Add the record to an index let saveResp = try await client.saveObject( indexName: indexName, body: record ) // Wait until indexing is done try await client.waitForTask( with: saveResp.taskID, in: indexName ) // Search for 'test' let searchResp: SearchResponses<Hit> = try await client.search( searchMethodParams: SearchMethodParams( requests: [ SearchQuery.searchForHits( SearchForHits( query: "test", indexName: indexName ) ) ] ) ) print(searchResp)
In production, don’t include your credentials in your code. Use environment variables instead.
-
Run:
swift run
.
If the command is successful, you’ll see the API response.
Next steps
You can view your new index in the Algolia dashboard.