ShiliangHM edited this page Nov 30, 2018 · 123 revisions

Huami Web API Documents for Developers

1. Overview

Welcome to the Huami API document.

Huami is the second largest manufacturer of wearables in the world. Our mission is to seamlessly connect our biomechanical signals and daily activities with smart data services to promote an active and healthy lifestyle while making our lives easier.

We’d like to help you build website or application by accessing user activity data tracked with our wearables (include Mi Band series, Amazfit ARC / PACE / EQUATOR / MOONBEAM).

2. App Registration

Please send registration email to partner@huami.com, with a short introduction to your organization and your application. In the follow-up registration emails, typically you need to provide information about an application such as:

  1. Application name

  2. Logo (CDN) URLs for the application

    Logo should contain name, and there should be one logo per language, such as English, Chinese, Japanese, Korean, and so on. URLs should all be httpS. E.g.

     httpS://CDN/en.SVG
     httpS://CDN/zh.SVG
  3. (CDN) URLs for users to obtain details of the application during authorization & admin

    There should be one URL per language, such as English, Chinese, Japanese, Korean, and so on. E.g.

     httpS://CDN/en.HTML
     httpS://CDN/zh.HTML
  4. A short description of the application

  5. A link to the application’s privacy policy

  6. A list of redirect URIs. This is required for Web apps only. If you build native Android and/or iOS apps, redirect URIs can be skipped. Instead, our User Consent SDK will return the authorization result.

Redirect URIs

Redirect URIs are a critical part of the OAuth flow. After a user successfully authorizes an application, the authorization server will redirect the user back to the application with either an authorization code or an access token in the URL. Because the redirect URI will contain sensitive information, it is critical that the service doesn’t redirect the user to arbitrary locations.

For users' privacy, non-app-protocol URIs should be httpS instead of http.

Unless ending with unencoded # or ?, # or ? will be appended. If URI contains unencoded #, ? will be appended unless ending with # or ?. Otherwise # will be appended unless ending with # or ?.

Scopes

Scope Description

profile

The profile scope is the basic user information

activity

The activity scope includes activity data, such as steps, distance, calories consumed, and active minutes

sleep

The sleep scope includes sleep logs and computed summary, such as sleep start time, wake time, duration of sleep

heartrate

The heartrate scope includes continuous heart rate data and computed summary.

motion

The motion scope includes raw motion sensor data per minute of a day, consists of 1440(total minutes of one day)*3 bytes

notifyme

allows 3rd-party applications to send notifications to a user, who typically gets notified by wristband/watch vibration, and then views the text message on wearables. Optionally, the user can tap their wearables, to acknowledge they have read the message. The read receipt will be pushed back to the message sender, see 5. Subscriptions.

sport

Including summary data for user activities like cycling, running

sportDetail

Including detail data for user activities like cycling, running

3. Authentication

OAuth 2.0 is supported for user authorization and API authentication. As the OAuth 2.0 framework defines, your applications need to obtain an Access Token when a Huami user authorizes your app to access their data. The Access Token should always be included in every HTTP request to Huami Web API. A Refresh Token should be preferrably obtained at the same time. For security season, Access Token has a short lifetime, while Refresh Token is designed to renew Access Tokens.

Huami provides SDK for native mobile apps. End users do not necessarily enter their user name and password again, but simply click agree button to grant consent. The SDK launches Huami Mifit app or Huami Amazfit app, which users usually have already installed and signed in to view their activity data on a daily basis. See the document below to integrate Huami User Consent SDK to your app.

:information_source:
The SDKs have NOT been formally released, but ready for early integration. To get the latest release schedule, please contact us.

If you are building a web site, please redirect users to the URI below. Be reminded of replacing those sample parameter values properly.

httpS://user.HuaMi.com/oauth/index.html#/?client_id=3rdPARTY&redirect_uri=REGISTERed&response_type=code&state=BLACK_BOX

HTTP protocol should be strictly followed, including proper encoding of all the parameters:

parameter mandatory description

client_id

Yes

Application id after registered @ HuaMi

redirect_uri

Yes

A list of redirect URL registered @HuaMi

response_type

No

  • "token" to directly redirect token(s) specified by above "token" parameter(s).

  • "code"(default) to redirect code by which to later exchange for token(s) specified by above "token" parameter(s).

login_hint

No

Optional hint for Oauth providers such as Google/HuaMi to prompt for whose password if not logged on before or which to proceed if multiple accounts logged on before

token

No

The type(s) of token to be returned upon user’s approval. NOTE: For security reason, Refresh token will NOT be returned for implicit grand mode (response_type=token).

  • Can be "token=access" for Access Token.

  • Can be "token=refresh" for Refresh Token unless "response_type=token".

  • Can be "token=access&token=refresh" for both Refresh Token (unless "response_type=token") & Access Token.

  • If not specified, request for Access Token.

region

No

for user.HuaMi.com to customize page(s) such as "cn-north-1" not to show Google/FaceBook since unavailable in China

  • user-US.HuaMi.com default is "us-west-2"

  • user-cn.HuaMi.com default is "cn-north-1"

  • Chinese default is "cn-north-1", non-Chinese default is "us-west-2", except for user-…​HuaMi.com

state

No

Anything you want to receive back from redirection

scope

No

Can be multiple "scope=SCOPE"s, or "scope=SCOPE;SCOPE". Each SCOPE syntax looks like the sample below (after encoding space ' ' to '+').

DATAintervalMONTHs+PROPERTY-PROPERTY@DEVICE@DEVICE,D9~17,D10~18
SCOPE portion mandatory description

DATA

Yes

profile/activity/sleep/motion/heartrate so far

interval

No

both "_daily" & "_hourly" activity/sleep so far unless specified individually

MONTHs

No

e.g. "6" months, All History will be authorized if none specified

+PROPERTY

No

can be multiple, for protected user data not to be authorized by default, e.g. "profile" property "weight" isn’t included by default, 3rd party can ask for "weight" explicitly by specifying "scope=profile+weight" (after encoding space ' ' to '+')

-PROPERTY

No

can be multiple, to reduce bandwidth, e.g. "heartrate-sync" to exclude Sync Time

DEVICE

No

can be multiple, data @ all devices will be authorized if none specified. equator/MoonBeam/arc/pace so far

D9~18

No

can be multiple, data @ all dates/times will be authorized if none specified. D for day, such as

  • lower case 's' for Sunday

  • 'M' for Monday

  • 'T' for Tuesday

  • 'W' for Wednesday

  • 't' for Thursday

  • 'F' for Friday

  • upper case 'S' for Saturday

Time range is optional, data @ whole day will be authorized if none specified. E.g. 10~18 for 10am through 6pm, default starting time is 0 if unspecified & default ending time is 24 if unspecified

data properties

profile

  • userId

  • gender

  • height

  • weight (excluded by default)

  • nickName

  • avatar

activity_daily

  • date (always included)

  • lastSyncTime

  • steps

  • distance

  • calories

activity_hourly

  • date (always included)

  • lastSyncTime

  • time (always included)

  • steps

  • calories

sleep_daily

  • date (always included)

  • lastSyncTime

  • start

  • stop

  • deepSleepTime

  • shallowSleepTime

  • wakeTime

sleep_hourly

  • date (always included)

  • lastSyncTime

  • start

  • stop

  • mode

motion

  • date (always included)

  • lastSyncTime

  • activeness

  • mode

  • steps

heartrate

  • date (always included)

  • lastSyncTime

  • heartRateData

User denying or failed authorization will also be redirected E.g. (see above for # or ? appending)

httpS://REGISTERed#error=ERROR&state=BLACK_BOX

Authorization Code Grant Flow

Authorization Code Grant Flow is a preferred for security. Please see RFC 6749. Authorization Code will be redirected for above "response_type=code" E.g.

httpS://REGISTERed?code=AUTHORIZATION&state=BLACK_BOX
Exchanging an Authorization Code for an Access Token

Once your service receives an Authorization Code, use it to exchange for access token.

:information_source:
Do not store your client secret in your client appliction. Making the request from a backend server protects your client secret from being stolen.
:information_source:
The authorization code will expire after 5 minutes and you will receive error like {"code":-1004, "message":"Invalid parameter 'code'"}

Request structure

POST /oauth2/access_token HTTP/1.1
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Host: auth.huami.com

client_id=clientId&client_secret=clientSecret&grant_type=authorization_code&redirect_uri=http%3A%2F%2Fwww.yourdomain.com&code=code

Request parameters

Parameter Mandatory Description

client_id

Yes

Application ID issued by HuaMi when registering application

client_secret

Yes

Secret assigned to your application

grant_type

Yes

The grant_type parameter must be set to 'authorization_code'

redirect_uri

Yes

This is the URI to which you want the user to be redirected after the authorization is complete. This must match the redirect URI that you have previously registered with the service

code

Yes

Authorization Code

Example response

HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Content-Length: 617

{"access_token":"TAQABAAAAAJ95lT4WrRdWtG3hog/0QvXTnUpL3FFxKOLBgm4JjIKJbSozXYxtltsQzBz0Z9PXDiIKBUOLMfjWX5Je6tGEdXLeaYeCEVS0dVYMWG+p+Y7avcVe0SWY4jITNGfuq/tlNLK9cACSkIW/L6Mnb9YNp4CzQDo7dU9WrxK87aOJ7gAlE4leZKeCM3+xLY3zRs3BGZEwrsCmEMqPr14rrD2KHny6aD2UvGQfXdVGVExe8jRbMLw2L2KdRWrxEW7vZRzXdw==","token_type":"Bearer","expires_in":43200,"refresh_token":"TAQEBAAAAAC7iIWnqI4uE6UgCUiBRg887o9H48QS3IhW5b8c4aJQtyn2ED73TeJKxhWhxVg5+e5lM8Gv5il9FWbQjG5rDKCVnLZ2VGxqrcj6pcAXrLmOQeTePl9dF507jX3awUjQ9RIi7PQhD5MzOlvNIciBhy6hrxU2u5pLt0uTWTJC36blvkwAmdZXQwIpxz2cJPfgTKWGGM1v4IT8uWkYRMWnvYUWOXoPvubp7MRRdVPyngtcbq3aAYCMMmbHilZs8x/jALQ=="}

Response fields

Path Type Description

access_token

String

Access token

token_type

String

Token type

expires_in

Number

access_token TTL in second

refresh_token

String

Refresh token, used to refresh access token

CURL request

$ curl 'https://auth.huami.com/oauth2/access_token' -i -X POST -H 'Accept: application/json' -H 'Content-Type: application/x-www-form-urlencoded' -d 'client_id=clientId&client_secret=clientSecret&grant_type=authorization_code&redirect_uri=REGISTERed&code=code'

Implicit Grant Flow

In the implicit flow, instead of issuing the client an authorization code, the client is issued an access token directly. However, this convenience should be weighed against the security implications of using implicit grants, such as being exposed to unauthorized parties (when the access token is transmitted in the URI fragment), or misuse of access token to impersonate resource owner.

Access/Refresh Token(s) will be redirected for above "token=access" and/or "token=refresh" E.g. (see above for # or ? appending)

httpS://REGISTERed#access_token=ACCESS_TOKEN&expires_in=SECONDsSINCE1970&state=BLACK_BOX

Making Requests

To make a request to the HuaMi Data API using OAuth 2.0, simply add an Authorization header to the HTTP request with the user’s access token. See 4. Accessing Data for detailed description of all data APIs.

Example Request:

GET https://api-open.huami.com/users/-/profile
Authorization: Bearer TAQABAAAAAJ95lT4WrRdWtG3hog/0QvXTnUpL3FFxKOLBgm4JjIKJbSozXYxtltsQzBz0Z9PXDiIKBUOLMfjWX5Je6tGEdXLeaYeCEVS0dVYMWG+p+Y7avcVe0SWY4jITNGfuq/tlNLK9cACSkIW/L6Mnb9YNp4CzQDo7dU9WrxK87aOJ7gAlE4leZKeCM3+xLY3zRs3BGZEwrsCmEMqPr14rrD2KHny6aD2UvGQfXdVGVExe8jRbMLw2L2KdRWrxEW7vZRzXdw==

Huami OAuth Error Code

Http Status code message

401

0

invalid token

400

-1001

Error parameter

400

-1002

Missing required parameter

500

-1003

Internal server error

400

-1004

Invalid parameter

400

-1009

partner has been offline, please contact the service provider

401

-1010

Unauthorized resources

401

-1011

User authorization has expired, please relogin again

400

-1012

Method type not allowd

400

-1013

Unsupported Media Type

401

-1015

The provided android package_id/code_signature or ios bundle_id is invalid

404

-2001

Not found

400

-2002

Bad request

Refreshing Tokens

Request structure

POST /oauth2/refresh_token HTTP/1.1
Authorization: Bearer TAQEBAAAAAC7iIWnqI4uE6UgCUiBRg887o9H48QS3IhW5b8c4aJQtyn2ED73TeJKxhWhxVg5+e5lM8Gv5il9FWbQjG5rDKCVnLZ2VGxqrcj6pcAXrLmOQeTePl9dF507jX3awUjQ9RIi7PQhD5MzOlvNIciBhy6hrxU2u5pLt0uTWTJC36blvkwAmdZXQwIpxz2cJPfgTKWGGM1v4IT8uWkYRMWnvYUWOXoPvubp7MRRdVPyngtcbq3aAYCMMmbHilZs8x/jALQ==
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Host: auth.huami.com

client_id=2882303761517363510&client_secret=gwsORlhbQn1MpWheXJJx2w%3D%3D&grant_type=refresh_token

Request headers

Name Description

Authorization

Auth credentials,The format should be assigned 'Bearer refresh_token'

Request parameters

Parameter Mandatory Description

client_id

Yes

Application ID issued by HuaMi when registered application

client_secret

Yes

Application Secret

grant_type

Yes

The grant_type parameter must be set to 'refresh_token'

Example response

HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Content-Length: 617

{"access_token":"TAQABAAAAAJ95lT4WrRdWtG3hog/0QvXTnUpL3FFxKOLBgm4JjIKJbSozXYxtltsQzBz0Z9PXDiIKBUOLMfjWX5Je6tGEdXLeaYeCEVS0dVYMWG+p+Y7avcVe0SWY4jITNGfuq/tlNLK9cACSkIW/L6Mnb9YNp4CzQDo7dU9WrxK87aOJ7gAlE4leZKeCM3+xLY3zRs3BGZEwrsCmEMqPr14rrD2KHny6aD2UvGQfXdVGVExe8jRbMLw2L2KdRWrxEW7vZRzXdw==","token_type":"Bearer","expires_in":43200,"refresh_token":"TAQEBAAAAAC7iIWnqI4uE6UgCUiBRg887o9H48QS3IhW5b8c4aJQtyn2ED73TeJKxhWhxVg5+e5lM8Gv5il9FWbQjG5rDKCVnLZ2VGxqrcj6pcAXrLmOQeTePl9dF507jX3awUjQ9RIi7PQhD5MzOlvNIciBhy6hrxU2u5pLt0uTWTJC36blvkwAmdZXQwIpxz2cJPfgTKWGGM1v4IT8uWkYRMWnvYUWOXoPvubp7MRRdVPyngtcbq3aAYCMMmbHilZs8x/jALQ=="}

Response fields

Path Type Description

access_token

String

Access token

token_type

String

Token type

expires_in

Number

Expire at some time stamp, UNIX time stamp(seconds)

refresh_token

String

Refresh token, used to refresh access token

CURL request

$ curl 'https://auth.huami.com/oauth2/refresh_token' -i -X POST -H 'Authorization: Bearer TAQEBAAAAAC7iIWnqI4uE6UgCUiBRg887o9H48QS3IhW5b8c4aJQtyn2ED73TeJKxhWhxVg5+e5lM8Gv5il9FWbQjG5rDKCVnLZ2VGxqrcj6pcAXrLmOQeTePl9dF507jX3awUjQ9RIi7PQhD5MzOlvNIciBhy6hrxU2u5pLt0uTWTJC36blvkwAmdZXQwIpxz2cJPfgTKWGGM1v4IT8uWkYRMWnvYUWOXoPvubp7MRRdVPyngtcbq3aAYCMMmbHilZs8x/jALQ==' -H 'Accept: application/json' -H 'Content-Type: application/x-www-form-urlencoded' -d 'client_id=2882303761517363510&client_secret=gwsORlhbQn1MpWheXJJx2w%3D%3D&grant_type=refresh_token'

Token Life Cycle

Access Token

The default lifetime of accessToken is 90 days, if user revoke the authorization to 3rd party, the token will be out of work immediately. If developer has special requirement, contact the service provider to modify the token lifetime

Refresh Token

The default lifetime of refreshToken is 10 years.

4. Accessing Data

See Huami Web API Reference for details.

5. Subscriptions

:information_source:
Subscription notification is not available yet.

Subscription notification is a near real-time solution to allow third-party applications to be notified when certain event happpens on Huami users. Your applications can listen and wait to receive the lastest user state-changed events, rather than constantly polling on user data.

This is a complementary technology to calling Web API. The content in notifications may not have all information your application needs. In that case, you application must make appropriate Web API calls to retrieve the actual data, see 4. Accessing Data. Also, for many reasons, notifications do NOT guarantee 100% delivery success rate. Your application design should accommodate that, e.g. retrieve user data, periodically or when your application being brought to foreground.

Notifications are essentially HTTP requests made by Huami to a URI you registered. Thus you will implement a service behind the URI, to process incoming requests and to interpret the event content inside.

To receive notification, your application also needs to obtain user consent, see 3. Authentication. Huami does NOT send you the notifications of users whose consent is NOT current. Similarly, only data types of the scopes allowed by the user will be sent.

Implementing Subscription Web API

You can choose any modern Web technology to implement your service, following the API definition below.

Request structure

POST /fake HTTP/1.1
Content-Type: application/json
Accept: application/json
Host: api-open.huami.com
Content-Length: 247

{
  "userId":"1000000296",
  "eventType":"userNotificationStateChange",
  "eventTime":1499736115,
  "resourceTime":1499736115,
  "data":"{\"messageId\":\"973092ed-2cbd-4c62-94a9-173df7bd90e3:2940419362109032751\",\"time\":1498214663,\"state\":\"MESSAGE_READ\"}"
}

Request parameters

Parameter Mandatory Description

userId

Yes

The ID of user whose state or data has changed.

eventType

Yes

The state-changed event type. For example, userNotificationStateChange, activityDataUpdated.

eventTime

Yes

The time of event occurred.

resourceTime

No

The datetime of changed resource data. Use this to determine the time span parameters when retrieving the actual data.

data

No

Extra information (in json object format) associated with the eventType. See below for details

The data field is a String in json format and its format is associated with the eventType value:

eventType Example Description

userNotificationStateChange

{"messageId":"e54d1d61-8246-48d1-9b9b-90b327b23dd5", "state":"read"}

Once 3rd-party app sends a message of notification to a user, it can track the notification state by receiving this event.

  • messageId, a unique identifier per message generated and returned upon user notification message creation. 3rd-party apps could correlate the state change event by this id.

  • state, read indicates a user has read the message.

physicalActivityStateChange

{"state":"asleep"}

this kind of event occurs when a user falls asleep, wakes up, or becomes other states.

  • state, indicates a user’s current physical activity state, e.g. asleep, awake.

Response structure Your service must respond HTTP Code 204 No Content, as an aknowledgement to a successful notification delivery.

HTTP/1.1 204 No Content

CURL request

$ curl 'https://api-open.huami.com/fake' -i -X POST \
    -H 'Content-Type: application/json' \
    -H 'Accept: application/json' \
    -d '{
          "userId":"1000000296",
          "eventType":"userNotificationStateChange",
          "eventTime":1499736115,
          "resourceTime":1499736115,
          "data":"{\"messageId\":\"973092ed-2cbd-4c62-94a9-173df7bd90e3:2940419362109032751\",\"time\":1498214663,\"state\":\"MESSAGE_READ\"}"
        }'

Design for High Availabity and Low Latency

Your service should respond as soon as possible. Store received events locally and process them later asynchorously. If your service cannot respond in two seconds, Huami will mark your service as failed to respond. Huami will retry three times in one minute, and eventually stop your subscription without warning.

HTTPS Only

To provent user data from being compromised on Internet trafic, Huami always sends HTTPS requests to default port 443. You must register a URI starting with HTTPS://.

:fire:
Self-signed certificates are not supported.

Verifying the Request

Huami puts a Huami-Signature header in every request for security. Your service must verify the imcoming requests have not been tampered. Signature verfication success proves the content of the request is indeed generated by Huami.

:information_source:
Attachers may resend or playback the request if they ever captured the request payload. Your service should handle those repeated requests, just like the same notification has been delivered more than once.
Huami-Signature

Signature is computed from the notification request payload with the standard RSA-SHA1 algorithm. The signature will be BASE64 encoded and then URL encoded. Pseudo code:

Url.encode(
  Base64.encode(
    RSA_SHA1.getSignature(request.payload)))

Your service decodes the signature in the opposite way as Huami did, then verifies the signature with the request body. If signature verification fails, your service should stop processing that notification.

Registering Subscription

Once you have completed your service code and deployed it on production environment, see 2. App Registration to register the URI. You are all set.

6. Help

If you encounter any issue, please try to search historical issue list first. If there is no similar issue or question, feel free to create a new one, and we will respond to all open issues in time.

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.