API Clients and REST API

Places.js Library

Important: The default way to use Places is through the Places.js library.

You can read more about how to use the Places.js library in the documentation section. The present section is describing alternative ways of accessing Places data. You should first checkout out the documentation for Places.js as well as the examples page to determine whether or not the clients are a better fit for your use case.

API Clients

JavaScript API Client

You can directly query the Places REST API using our JavaScript API client, either in browsers or with Node.js.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// var algoliasearch = require('algoliasearch');
var places = algoliasearch.initPlaces('YOUR_PLACES_APP_ID', 'YOUR_PLACES_API_KEY');
places
  .search(/*{REST API Params}*/, function(err, res) {
    if (err) {
      throw err;
    }
    console.log(res);
  });

places
  .getObject(/*{REST API Params}*/, function(err, res) {
    if (err) {
      throw err;
    }
    console.log(res);
  });

Note: Like with the Places.js library, you need to provide your Places App credentials in order for the clients to function properly. If you do not have a Places application, you can create one by signing up for free.

PHP API Client

You can directly query the Places REST API with our PHP API Client, so that you can do backend Places searches.

1
2
3
4
5
6
7
8
9
<?php

$appId = 'YOUR_PLACES_APP_ID';
$apiKey = 'YOUR_PLACES_API_KEY';

$places = \AlgoliaSearch\Client::initPlaces($appId, $apiKey);

$result = $places->search('Paris');
var_dump($result);

Note: Like with the Places.js library, you need to provide your Places App credentials in order for the clients to function properly. If you do not have a Places application, you can create one by signing up for free.

Swift API Client

You can directly query the Places REST API with our Swift API Client, so that you can do backend Places searches.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// initialize client
let places = PlacesClient(appID: "YOUR_PLACES_APP_ID", apiKey: "YOUR_PLACES_API_KEY")

// craft a query
let query = PlacesQuery()
query.query = "Paris"
query.type = .city
query.hitsPerPage = 10
query.aroundLatLngViaIP = false
query.aroundLatLng = LatLng(lat: 32.7767, lng: -96.7970) // Dallas, TX, USA
query.language = "en"
query.countries = ["fr", "us"]

// search
places.search(query) { (content, error) in
    // content?["hits"] to access the hits
}

Note: Like with the Places.js library, you need to provide your Places App credentials in order for the clients to function properly. If you do not have a Places application, you can create one by signing up for free.

Android API Client

You can directly query the Places REST API with our Android API Client, so that you can do backend Places searches.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// initialize client
PlacesClient places = new PlacesClient("YOUR_PLACES_APP_ID", "YOUR_PLACES_API_KEY");

// craft a query
PlacesQuery query = new PlacesQuery();
query.setQuery("Paris");
query.setType(PlacesQuery.Type.CITY);
query.setHitsPerPage(10);
query.setAroundLatLngViaIP(false);
query.setAroundLatLng(new PlacesQuery.LatLng(32.7767, -96.7970)); // Dallas, TX, USA
query.setLanguage("en");
query.setCountries("fr", "us");

// search
places.searchAsync(query, new CompletionHandler() {
    ...
});

REST API

The Algolia Places REST API supports HTTPS and is available via the https://places-dsn.algolia.net domain (leveraging our Distributed Search Network infrastructure).

In order to guarantee a very high-availability, we recommend to implement a retry strategy on the following hosts if the https://places-dsn.algolia.net call fails:

  • https://places-1.algolianet.com,
  • then https://places-2.algolianet.com,
  • then https://places-3.algolianet.com.

Endpoints

To search using the Algolia Places REST API, you need to target the /1/places/query endpoint with a POST request.

1
$ curl -X POST 'https://places-dsn.algolia.net/1/places/query' --data '{"query": "Paris"}'

Note: The relative path prefix /1/ indicates that we are currently using version 1 of the API.

Get by objectID

To get an Algolia Places Record using the REST API, you need to target the /1/places/{objectID} endpoint with a GET request.
Replace {objectID} by the objectID you whish to query.

1
$ curl -X GET 'https://places-dsn.algolia.net/1/places/111781_17807753'

Reverse geocoding

Reverse geocoding means converting a location (latitude and longitude) to a readable address.

Note: aroundLatLng parameter is mandatory. The only optional parameters permitted for this endpoint are hitsPerPage and language.

1
$ curl -X GET 'https://places-dsn.algolia.net/1/places/reverse?aroundLatLng=48.880379,%202.327007&hitsPerPage=5&language=fr'

Authentication

If you're using the authenticated version of our API (higher rate-limits), you'll need to authenticate yourself. This is done via the following HTTP headers:

  • X-Algolia-Application-Id,
  • and X-Algolia-API-Key.
1
2
3
4
$ curl -X POST 'https://places-dsn.algolia.net/1/places/query' \
  -H 'X-Algolia-Application-Id: YourApplicationId' \
  -H 'X-Algolia-API-Key: YourAPIKey' \
  --data '{"query": "Paris"}'

Search parameters

Those are the available query parameters you can use to filter your search results:

Option Description
type

Type: string

Restrict the search results to a specific type.

Available types:

  • city
  • country
  • address
  • busStop
  • trainStation
  • townhall
  • airport

Default: Search in all types.

hitsPerPage

Type: number

Specifies how many results you want to retrieve per search.

Default: 20.

page

Type: number

Specifies the current page to retrieve results for. First page starts at 0.

Default: 0.

language

Type: string

If specified, restrict the search results to a single language. You can pass two letters country codes (ISO 639-1).

Warning: language parameter is case sensitive and should be lowercase otherwise it will fallback to default language.

countries

Type: string

If specified, restrict the search results to a specific list of comma-separated countries. You can pass two letters country codes (ISO 3166-1).

Default: Search on the whole planet.

Warning: country codes must be lower-cased.

aroundLatLng

Type: string

Force to first search around a specific latitude longitude. The option value must be provided as a string: latitude,longitude like 12.232,23.1.

The default is to search around the location of the user determined via his IP address (geoip).

aroundLatLngViaIP

Type: boolean

Whether or not to first search around the geolocation of the user found via his IP address. This is true by default.

aroundRadius

Type: number

Radius in meters to search around the latitude/longitude. Otherwise a default radius is automatically computed given the area density.

getRankingInfo

Type: boolean

Controls whether the _rankingInfo object should be included in the hits. This defaults to false.

The _rankingInfo object for a Places query is slightly different from a regular Algolia query and you can read up more about the difference and how to leverage them in our guide.

For instance, to search for cities in the US and in France, you would do:

1
2
$ curl -X POST 'https://places-dsn.algolia.net/1/places/query' \
  --data '{"query": "Paris", "type": "city", "countries": ["us", "fr"]}'

HTTP headers

You can use the regular X-Forwarded-For HTTP header to override the source IP address used to resolve the geo-location of the user. This is particularly useful when you want to use the API from your backend as if it was from your end-users locations.

1
2
3
$ curl -X POST 'https://places-dsn.algolia.net/1/places/query' \
  -H 'X-Forwarded-For: 1.2.3.4' \
  --data '{"query": "Paris"}'

JSON answer

The API answers is using the JSON format and looks like:

1
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
{
  "hits": [{
    "objectID": "145746683_7444",
    "locale_names": {
      "ar": ["باريس"],
      "ru": ["Париж"],
      "fr": ["Paris", "Lutèce"],
      "it": ["Parigi"],
      "default": ["Paris"],
      "pl": ["Paryż"],
      "hu": ["Párizs"],
      "ja": ["パリ"],
      "nl": ["Parijs"],
      "es": ["París"],
      "zh": ["巴黎"]
    },
    "city": {
      "default": ["Paris"],
      // ... other languages
    },
    "county": {
      "default": ["Paris"],
      // ... other languages
    },
    "administrative": ["Île-de-France"],
    "country": {
      "default": "France",
      // ... other languages
    },
    "country_code": "fr",
    "postcode": ["75000"],
    "population": 2243833,
    "_geoloc": {
      "lat": 48.8564,
      "lng": 2.3521
    },
    "_highlightResult": {
      "locale_names": {
        "default": [{
            "value": "<em>Paris</em>",
            "fullyHighlighted": true,
            "matchedWords": ["paris"],
            "matchLevel": "full"
          }]
          // [...]
      },
      "city": {
        // [...]
      },
      "county": {
        // [...]
      },
      "country": {
        // [...]
      },
      "postcode": [
        // [...]
      ],
      "administrative": [
        // [...]
      ]
    }
  }],
  "nbHits": 1,
  "query": "Paris"
}
Property Description
locale_names

List of names of the place. If no language parameter is specified, retrieves all of them.

Examples:

  • Paris
  • 589 Howard Street
city

List of the associated city names. If no language parameter is specified, retrieves all of them.

county

List of the associated county names. If no language parameter is specified, retrieves all of them.

administrative

List of associated administrative region names.

Examples:

  • Pays de la Loire
  • Texas
  • Catalunya
country

Associated country name.

countryCode

Two letters country code (ISO 639-1).

postcode

List of associated postcodes.

population

Associated population.

_geoloc

Associated list of latitude and longitude.

Examples:

  • [{lat: 48.797885, lng: 2.337034}]
_highlightResult

The associated highlighting information.

Note: The non-documented attributes of the JSON answer may change, don't rely on them.

Alternative JSON answer format

When you provide the language parameter, only data for that language will be returned.

Here is what it would look like if you are using the fr language for the Paris query:

1
2
3
4
5
6
7
8
{
  "hits": [{
    "objectID": "145746683_7444",
    "locale_names": ["Paris", "Lutèce"],
    "city": ["Paris"],
    // ...
  }],
}

Warning: In case you provide a non existing language, the engine will fallback to
the default language and only display flattened values for that one resulting in
the same output as in the last example.

Query strategy

The Algolia Places REST API leverages Algolia's Search API, the OpenStreetMap and the GeoNames data.

When you perform an Algolia Places Query:

  1. If you don't specify any aroundLatLng query parameter or if your source IP address isn't geo-localized, results will come from all around the world.
  2. If you specify an aroundLatLng query parameter or if your source IP address is geo-localized, results will be composed by:
    • Places around you (<10km),
    • Places in your country,
    • Popular places all around the world.
  3. Specifying a country query parameter will override this behavior, restricting the results to come from a subset of the countries.
  4. Numerical tokens are considered as optional words.
  5. Stopwords in the middle of the query are removed from the underlying search query (performance and relevancy purposes).
  6. Popular cities will always be retrieved first.
  7. If both a city and an address are matching, the city will be retrieved first.
  8. If the query doesn't retrieve any results, we fallback on a degraded query strategy: all words are considered optional and we only target cities.