Examples

Quick Start

Want to jump right in? Below is a quick overview of how to get started using the radar-python library to power location based applications. Signup for your free account here https://radar.io/signup and grab your API keys to get started.

from radar import RadarClient

# initialize client with your project's secret key
SECRET_KEY = "<YOUR SECRET KEY>"
radar = RadarClient(SECRET_KEY)

# create a geofence
data = {
    "description": "Example Store",
    "type": "circle",
    "coordinates": [-73.98706, 40.7041029],
    "radius": 100,
    "tag": "store",
    "externalId": "123",
}
new_geofence = radar.geofences.create(data=data)

# Geocode an IP address, converting IP address to country, state if available

ip_location = radar.geocode.ip(ip="107.77.199.117")
"""
>>> print(ip_location)
{
  "city": "Atoka",
  "country": "United States",
  "countryCode": "US",
  "countryFlag": "\ud83c\uddfa\ud83c\uddf8",
  "latitude": 34.385929107666016,
  "longitude": -96.12832641601562,
  "meta": {
    "code": 200
  },
  "postalCode": "74525",
  "state": "Oklahoma",
  "stateCode": "OK"
}
"""

# Compare a route by bike vs foot

origin = (40.7041029, -73.98706)
destination = (40.7141029, -73.99706)
routes = radar.route.distance(origin, destination, modes="bike,foot")
"""
>>> print(f"by foot: {routes.foot}\nby bike: {routes.bike}")
by foot: <distance=2.8 km duration=34 mins>
by bike: <distance=3.2 km duration=12 mins>
"""

# Let a user know what hotels are nearby using place search
user_location = (40.7043, -73.9867)
radar.search.places(near=user_location, categories="hotel-lodging")
"""
[
    <Radar Place: _id='5ded545230409c49f439d943' name='1 Hotel Brooklyn Bridge' categories=['hotel-lodging', 'hotel']>,
    <Radar Place: _id='59c1f5898be4c5ce940b559f' name='Dazzler Hotels' categories=['hotel-lodging', 'inn', 'hotel', 'resort']>,
    <Radar Place: _id='59bf2f8d8be4c5ce9409d9f9' name='Hotel St. George' categories=['hotel-lodging', 'hotel']>,
    <Radar Place: _id='5ded528630409c49f41b36a1' name='Hampton Inn' categories=['hotel-lodging', 'hotel']>,
    <Radar Place: _id='59c1f5898be4c5ce940b559c' name='Hampton Inn Brooklyn Downtown' categories=['hotel-lodging', 'hotel', 'inn']>
]
"""

Initialization

Everything goes through the radar client, so start by initializing RadarClient with your API keys:

>>> from radar import RadarClient
>>> radar = RadarClient('secret')

The radar client provides access to all the radar API’s such as geofences, places, geocoding, search. Examples for each endpoint are included below.

Geofences

Geofences represent custom regions or places monitored in your project. Depending on your use case, a geofence might represent a retail store, a neighborhood, and so on.

Radar geofencing is more powerful than native iOS or Android geofencing, with cross-platform support for unlimited geofences, polygon geofences, and stop detection.

https://radar.io/documentation/geofences

from radar import RadarClient

# initialize client with your project's secret key
SECRET_KEY = "<YOUR SECRET KEY>"
radar = RadarClient(SECRET_KEY)

# create a geofence
data = {
    "description": "Example Store",
    "type": "circle",
    "coordinates": [-73.98706, 40.7041029],
    "radius": 100,
    "tag": "store",
    "externalId": "123",
}
new_geofence = radar.geofences.create(data=data)

# get a geofence by tag and externalId
geofence = radar.geofences.get(tag="store", externalId="123")
print(geofence)

# list geofences
for geofence in radar.geofences.list():
    print(f"Geofence: {geofence._id} - {geofence.description}")

# list users in a geofence
users_in_geofence = radar.geofences.list_users(tag="store", externalId="123")

# delete a geofence, can call geofence.delete() if it's already been fetched
radar.geofences.delete(tag="store", externalId="123")

Events

An event represents a change in user state. Events can be uniquely referenced by Radar _id.

https://radar.io/documentation/api#events

from radar import RadarClient

# initialize client with your project's secret key
SECRET_KEY = "<YOUR SECRET KEY>"
radar = RadarClient(SECRET_KEY)

# get an event by id
event = radar.events.get(id="123")
print(event)

# list events
for event in radar.events.list():
    print(f"Event: {event.type} at {event.createdAt}")

# list events from a certain time window
from datetime import datetime, timedelta, time

yesterday = datetime.now() - timedelta(days=1)
yesterday_9am = datetime.combine(yesterday, time(9))
yesterday_11am = datetime.combine(yesterday, time(11))
radar.events.list(createdAfter=yesterday_9am, createdBefore=yesterday_11am)

# verify an event
radar.events.verify(id="123", "accept")
radar.events.verify(id="123", value=1)

# delete an event, can call event.delete() if it's already been fetched
radar.events.delete(id="123")

Using this method, authentication happens during then initialization of the object. If the authentication is successful, the retrieved session cookie will be used in future requests. Upon cookie expiration, authentication will happen again transparently.

Users

A user represents a user tracked in your project. Users can be referenced by Radar _id, userId, or deviceId

https://radar.io/documentation/api#users

from radar import RadarClient

# initialize client with your project's secret key
SECRET_KEY = "<YOUR SECRET KEY>"
radar = RadarClient(SECRET_KEY)

# get a user by _id, externalId, or deviceId
user = radar.user.get("123")
print(user)

# list the 50 most recently updated users, and any geofences they're in
for user in radar.users.list(limit=50):
    print(f"User: {user._id}, last updated at {user.updatedAt}")
    for geofence in user.geofences:
        print(f"...in geofence {geofence.description}")

# delete a user, can call user.delete() if it's already been fetched
radar.users.delete("123")

Context

Gets context for a location without sending device or user identifiers to the server.

https://radar.io/documentation/api#context

from radar import RadarClient

# initialize client with your project's secret key and publishable key
SECRET_KEY = "<YOUR SECRET KEY>"
PUB_KEY = "<YOUR PUB KEY>"
radar = RadarClient(secret_key=SECRET_KEY, pub_key=PUB_KEY)

# Get context for a location without sending device or user identifiers to the server.
coordinates = (40.702640, -73.990810)
context = radar.context.get(coordinates=coordinates)
if "place" in dir(context):
    print(f"Location is at place: {context.place.name}")

print(context)
"""
{
  "live": false,
  "geofences": [],
  "place": {
    "_id": "5dc9ada22004860034be2f80",
    "categories": [
      "food-beverage",
      "cafe",
      "coffee-shop"
    ],
    "chain": {
      "domain": "starbucks.com",
      "name": "Starbucks",
      "slug": "starbucks"
    },
    "location": {
      "coordinates": [
        -73.990924,
        40.702719
      ],
      "type": "Point"
    },
    "name": "Starbucks"
  },
  "country": {
    "_id": "5cf694f66da6a800683f4d71",
    "code": "US",
    "name": "United States",
    "type": "country"
  },
  "state": {
    "_id": "5cf695096da6a800683f4e7f",
    "code": "NY",
    "name": "New York",
    "type": "state"
  }
  "dma": {
    "_id": "5cf695016da6a800683f4e06",
    "code": "501",
    "name": "New York",
    "type": "dma"
  },
  "postalCode": {
    "_id": "5cf695286da6a800683f5911",
    "code": "11201",
    "name": "11201",
    "type": "postalCode"
  },
}
"""

Geocode

https://radar.io/documentation/api#geocode

from radar import RadarClient

# initialize client with your project's secret key
SECRET_KEY = "<YOUR SECRET KEY>"
radar = RadarClient(SECRET_KEY)

# Geocodes an address, converting address to coordinates.

address = radar.geocode.forward(query="20 jay st brooklyn")[0]
print(address)
print(f"{address.latitude}, {address.longitude}")
"""
>>> print(address)
{
  "borough": "Brooklyn",
  "city": "New York",
  "confidence": "exact",
  "country": "United States",
  "countryCode": "US",
  "countryFlag": "\ud83c\uddfa\ud83c\uddf8",
  "formattedAddress": "20 Jay Street, Brooklyn, New York, NY 11201 USA",
  "geometry": {
    "coordinates": [
      -73.986675,
      40.704262
    ],
    "type": "Point"
  },
  "latitude": 40.704262,
  "longitude": -73.986675,
  "addressLabel": "20 Jay Street",
  "neighborhood": "DUMBO",
  "number": "20",
  "postalCode": "11201",
  "state": "New York",
  "stateCode": "NY",
  "street": "Jay Street"
}
>>> print(f"{address.latitude}, {address.longitude}")
40.704262, -73.986675
"""

# Reverse geocodes a location, converting coordinates to address.

address = radar.geocode.reverse(coordinates=(40.7041895, -73.9867797))[0]
"""
>>> print(address)
{
  "borough": "Brooklyn",
  "city": "New York",
  "country": "United States",
  "countryCode": "US",
  "countryFlag": "\ud83c\uddfa\ud83c\uddf8",
  "distance": 0.015,
  "formattedAddress": "20 Jay St, Brooklyn, New York, NY USA",
  "geometry": {
    "coordinates": [
      -73.986802,
      40.704053
    ],
    "type": "Point"
  },
  "latitude": 40.704053,
  "longitude": -73.986802,
  "addressLabel": "20 Jay St",
  "neighborhood": "DUMBO",
  "number": "20",
  "state": "New York",
  "stateCode": "NY",
  "street": "Jay St"
}
>>> print(address.formattedAddress)
20 Jay St, Brooklyn, New York, NY USA
"""


# Geocode an IP address, converting IP address to country, state if available

ip_location = radar.geocode.ip(ip="107.77.199.117")
"""
>>> print(ip_location)
{
  "city": "Atoka",
  "country": "United States",
  "countryCode": "US",
  "countryFlag": "\ud83c\uddfa\ud83c\uddf8",
  "latitude": 34.385929107666016,
  "longitude": -96.12832641601562,
  "meta": {
    "code": 200
  },
  "postalCode": "74525",
  "state": "Oklahoma",
  "stateCode": "OK"
}
"""

Route

https://radar.io/documentation/api#route

from radar import RadarClient

# initialize client with your project's secret key
SECRET_KEY = "<YOUR SECRET KEY>"
radar = RadarClient(SECRET_KEY)

# Compare a route by bike vs foot

origin = (40.7041029, -73.98706)
destination = (40.7141029, -73.99706)
routes = radar.route.distance(origin, destination, modes="bike,foot")
"""
>>> print(f"by foot: {routes.foot}\nby bike: {routes.bike}")
by foot: <distance=2.8 km duration=34 mins>
by bike: <distance=3.2 km duration=12 mins>
"""

# Whats the quickest way to get from a user's origin to destination?

origin = (40.7041029, -73.98706)
destination = (40.7141029, -73.99706)
routes = radar.route.distance(origin, destination, modes="transit,car,bike,foot")

(quickest_mode, quickest_route) = min(
    [("car", routes.car), ("transit", routes.transit), ("bike", routes.bike)],
    key=lambda route: route[1].duration.value,
)
"""
>>> print(f"quickest route is by {quickest_mode}, which will take {quickest_route.duration.value:.2f} min")
quickest route is by car, which will take 9.57 min
"""