Read Sleep Data

Sleep is represented by sessions in Google Fit, which can optionally contain segments indicating finer-grained types of sleep.

Sessions can optionally have segments. Segments have more granular details about sleep data, for example, if it was light, deep or REM sleep:

Sleep activity values
Activity type Value
Sleep 72
Light sleep 109
Deep sleep 110
REM 111
Awake (during sleep cycle) 112

The write sleep data guide shows how both granular and non-granular sleep data is represented in Fit.

Android

The follow samples uses a SessionClient to retrieve data from Fit, for both cases.

// Note: The android.permission.ACTIVITY_RECOGNITION permission is
// required to read DataType.TYPE_ACTIVITY_SEGMENT
SessionReadRequest request = new SessionReadRequest.Builder()
        .readSessionsFromAllApps()
        // Activity segment data is required for details of the fine-
        // granularity sleep, if it is present.
        .read(DataType.TYPE_ACTIVITY_SEGMENT)
        .setTimeInterval(1576690819, 1576750401, TimeUnit.SECONDS)
        .build();

Task<SessionReadResponse> task = sessionClient.readSession(request);

task.addOnSuccessListener(response -> {
    // Filter the resulting list of sessions to just those that are sleep.
    List<Session> sleepSessions = response.getSessions().stream()
            .filter(s -> s.getActivity().equals(FitnessActivities.SLEEP))
            .collect(Collectors.toList());

    for (Session session : sleepSessions) {
        Log.d("AppName", String.format("Sleep between %d and %d",
                session.getStartTime(TimeUnit.SECONDS),
                session.getEndTime(TimeUnit.SECONDS)));

        // If the sleep session has finer granularity sub-components, extract them:
        List<DataSet> dataSets = response.getDataSet(session);
        for (DataSet dataSet : dataSets) {
            for (DataPoint point : dataSet.getDataPoints()) {
                // The Activity defines whether this segment is light, deep, REM or awake.
                String sleepStage = point.getValue(Field.FIELD_ACTIVITY).asActivity();
                long start = point.getStartTime(TimeUnit.SECONDS);
                long end = point.getEndTime(TimeUnit.SECONDS);
                Log.d("AppName",
                        String.format("\t* %s between %d and %d", sleepStage, start, end));
            }
        }
    }
});

REST

Retrieving sleep sessions using the REST API is a two stage process:

  1. Retrieve a list of sessions setting the activityType parameter to 72 (SLEEP). Note: You can use a startTime and endTime, or use a pageToken to retrieve new sessions since the previous request.

    HTTP method

    GET
    

    Request URL

    https://www.googleapis.com/fitness/v1/users/me/sessions?startTime=2019-12-05T00:00.000Z&endTime=2019-12-17T23:59:59.999Z&activityType=72
    

    Response

    An example Session response might be:

    {
     "session": [
        {
         "id": "Sleep1575505620000",
         "name": "Sleep",
         "description": "",
         "startTimeMillis": "1575505620000",
         "endTimeMillis": "1575526800000",
         "modifiedTimeMillis": "1575590432413",
         "application": {
          "packageName": "com.example.sleep_tracker"
         },
         "activityType": 72  // Sleep
        },
        {
         "id": "Run2939075083",
         "name": "Mud",
         "description": "",
         "startTimeMillis": "1576594403000",
         "endTimeMillis": "1576598754000",
         "modifiedTimeMillis": "1576616010143",
         "application": {
          "packageName": "com.example.run_tracker"
         },
         "activityType": 8  // Running
        }
      ],
     "deletedSession": [],
     "nextPageToken": "1576598754001"
    }
    
  2. To obtain details of sleep stages for each session (if present), use the following request for each session in the filtered list:

    HTTP method

    POST
    

    Request URL

    https://www.googleapis.com/fitness/v1/users/userId/dataset:aggregate
    

    Request body

    {
      "aggregateBy": [
        {
          "dataTypeName": "com.google.activity.segment"
        }
      ],
      "endTimeMillis": 1575609060000,
      "startTimeMillis": 1575591360000
    }
    

    Response

    If your request was successful, you'll get a 200 OK HTTP response status code. The response body contains a JSON representation of activity segments that comprise the sleep session. Each intVal represents the sleep activity type

    {
     "bucket": [
      {
       "startTimeMillis": "1575591360000",
       "endTimeMillis": "1575609060000",
       "dataset": [
        {
         "point": [
          {
           "startTimeNanos": "1575591360000000000",
           "endTimeNanos": "1575595020000000000",
           "dataTypeName": "com.google.activity.segment",
           "originDataSourceId": "...",
           "value": [
            {
             "intVal": 109, // Light sleep
             "mapVal": []
            }
           ]
          },
          {
           "startTimeNanos": "1575595020000000000",
           "endTimeNanos": "1575596220000000000",
           "dataTypeName": "com.google.activity.segment",
           "originDataSourceId": "...",
           "value": [
            {
             "intVal": 72, // Sleep
             "mapVal": []
            }
           ]
          },
    
          // .... more datapoints
    
          {
           "startTimeNanos": "1575605940000000000",
           "endTimeNanos": "1575609060000000000",
           "dataTypeName": "com.google.activity.segment",
           "originDataSourceId": "...",
           "value": [
            {
             "intVal": 109, // Light sleep
             "mapVal": []
            }
           ]
          }
         ]
        }
       ]
      }
     ]
    }