Python client

Installing

Install the package using pip:

pip install terra-python

You can now import the Terra class from terra.base_client:

from terra.base_client import Terra

Initialise the Terra Object

The first step is to initialise the Terra object using your api_key, dev_id and your signing secret that can be found in: https://dashboard.tryterra.co/api.customise

parameterdescriptiontype
api_keyYour terra API key. You can find it in your terra dashboard (see Customize API settings)str
dev_idYour terra developer ID. You can find it in your terra dashboard (see Customize API settings)str
secretThe signing secret for webhooks. You can find it in your terra dashboard (see Customize API settings)str
terra = Terra(api_key='YOUR API KEY', dev_id='YOUR DEV ID', secret="YOUR TERRA SECRET")

You can now access most of the endpoints offered by the Terra API!

Listing Providers

You access the list of providers using the following method:

api_response = terra.list_providers()

Get the parsed response:

parsed_api_response = api_response.get_parsed_response()

The parsed object will be a ProvidersResponse object:

ProvidersResponse(status: str, providers: List[str])

User Authentication

  • REST Authentication:

Using the terra object you just initialised, you can call the 'generate_authentication_url' method which will return a TerraApiResponse object.

parameterdescriptiontype
resourceThe provider you want to authenticate your user with, for example: garmin, polar...str
auth_success_redirect_urlURL to redirect to upon successful authenticationstr
auth_failure_redirect_urlURL to redirect to upon unsuccessful authenticationstr
reference_idID of a user in your app, which will be returned at the end of a successful authenticationstr
api_response = terra.generate_authentication_url(resource="provider", auth_success_redirect_url="https://success.url", auth_failure_redirect_url="https://failure.url", reference_id="ID of the user in your project")

You can get the JSON representation of the reponse:

json_api_resposne = api_response.get_json()

Or the parsed representation:

parsed_api_response = api_response.get_parsed_response()

The parsed Rest Authentication object is UserAuthUrl:

UserAuthUrl(status: str, expires_in: int, auth_url: str, user_id: str)
  • Widget Authentication:

Using the terra object you just initialised, you can call the 'generate_widget_session' method which will return a TerraApiResponse object.

parameterdescriptiontype
providersA list of the names of the providers to display on widget wearable selection screen. Leaving it empty will show all providers.List of str
auth_success_redirect_urlURL to redirect to upon successful authenticationstr
auth_failure_redirect_urlURL to redirect to upon unsuccessful authenticationstr
reference_idID of a user in your app, which will be returned at the end of a successful authenticationstr
languageThe language to display widget instr

Generating a widget session for only some providers:

api_response = terra.generate_widget_session(providers=["provider1", "provider2"], auth_success_redirect_url="https://success.url", auth_failure_redirect_url="https://failure.url", reference_id="ID of the user in your project",language="en")

Generating a widget session for all providers:

api_response = terra.generate_widget_session(providers=[], auth_success_redirect_url="https://success.url", auth_failure_redirect_url="https://failure.url", reference_id="ID of the user in your project",language="en")

You can get the JSON representation of the response:

json_api_resposne = api_response.get_json()

Or the parsed representation:

parsed_api_response = api_response.get_parsed_response()

The parsed Widget Authentication object is WidgetSession:

WidgetSession(expires_in: int, status: str, session_id: str, url: str)

The User Object

The user object can be created from the user_id using the following method:

terra_user = terra.from_user_id(user_id='ID OF THE USER')

The User object definition is the following:

User(user_id: str, provider: str, last_webhook_update: str)

List Subscribed Users

You access the list of users using the following method:

api_response = terra.list_users()

Get the parsed response object, which will be a SubscribedUsers object:

parsed_api_response = api_response.get_parsed_response()
SubscribedUsers(users: List[User])

You can access each user using the following loop:

for terra_user in parsed_api_response.users:
  #do something

Getting Data

  • Requesting the data:

You can request any type of data using the User object, using the following methods:

  • get_activity
  • get_body
  • get_nutrition
  • get_daily
  • get_sleep
  • get_athlete
  • get_menstruation
parameterdescriptiontype
start_dateDatetime object for which to fetch datadatetime.datetime
end_dateOptional end_date for which to fetch data - if not set, will default to start_date + 24h according to current API specificationsdatetime.datetime
to_webhookWhether to send data to registered webhook URL or return as a response bodybool

Example:

api_response = terra_user.get_activity(start_date= datetime.strptime('2022-07-29','%Y-%m-%d'), to_webhook = False )

You can get the JSON representation of the response:

json_api_resposne = api_response.get_json()

Or the parsed representation:

parsed_api_response = api_response.get_parsed_response()

The parsed object will be one of the following:

DataReturned(user: User, type: str, data: List[TerraDataModel])
NoDataReturned(user: User, status: str, message: str)
SentToWebhook(status: str, message: str)

The TerraDataModel objects can be found here: https://tryterra.github.io/terra-client-python/terra/models/v2.html

Webhooks

  • Handling the Webhooks:

Parsing Terra webhooks has never been easier! You can setup an endpoint that recieves POST requests.

Using the handle_flask_webhook method:

parameterdescriptiontype
requestThe flask.request object received by the endpointflask.request
@app.route('/webhook', methods=['POST'])
def recieving_hooks():
  
    api_response = terra.handle_flask_webhook(request)
    parsed_api_response = api_response.get_parsed_response()
    
    #do something
    
    return

Using the handle_webhook method:

parameterdescriptiontype
payloadThe decoded payload of the post request recievedstr
terra_signature_headerThe terra-signature param in the header of the post request recievedstr
@app.route('/webhook', methods=['POST'])
def recieving_hooks():
  
    api_response = terra.handle_webhook(request.get_data().decode("utf-8"),request.headers["terra-signature"])
    parsed_api_response = api_response.get_parsed_response()
    
    #do something
    
    return
  • Parsed Webhooks:

The parsed webhooks can be of multiple types:

DataReturned(user: User, type: str, data: List[TerraDataModel])
NoDataReturned(user: User, status: str, message: str)
AccessRevokedHookResponse(user: User, message: str)
AuthHookResponse(reference_id: str, user: User, widget_session_id: str)
UserReauthHookResponse(old_user: User, new_user: User, message: str)
UserDeauthHookResponse(user: User, message: str)
ConnectionErrorHookResponse(user: User, message: str)
GoogleNoDataSourceHookResponse(user: User, message: str)
RequestProcessingHookResponse(user: User, message: str)
RequestCompletedHookResponse(user: User, message: str)