Write Sleep Data

Your app can read and write granular sleep data. This includes light sleep, deep sleep, REM, and awake activities from the FitnessActivities enumerated type. To write sleep data you must create a session of type FitnessActivities.SLEEP. Sleep data must be encapsulated in a session if it is to appear in the user’s Journal in the Google Fit App.

Optionally, insert activity segments (inside session interval) of types to represent stages of sleep

No-granularity example

To write a night of sleep with no stage granularity, follow the example below. Create a session with start and end time, and the activity SLEEP.

Android

// Create the sleep session
Session session = new Session.Builder()
    .setName(sessionName)
    .setIdentifier(identifier)
    .setDescription(description)
    .setStartTime(startTime, TimeUnit.MILLISECONDS)
    .setEndTime(endTime, TimeUnit.MILLISECONDS)
    .setActivity(FitnessActivities.SLEEP)
    .build();

// Build the request to insert the session.
SessionInsertRequest request = new SessionInsertRequest.Builder()
    .setSession(session)
    .build();

// Insert the session into Fit platform
Log.i(TAG, "Inserting the session in the Sessions API");
Fitness.getSessionsClient(this, GoogleSignIn.getLastSignedInAccount(this))
        .insertSession(request)
        .addOnSuccessListener(
            // At this point, the session has been inserted and can be read.
            unused -> Log.i(TAG, "Session insert was successful!"))
        .addOnFailureListener(
            e ->
                Log.i(TAG, "There was a problem inserting the session: " +
                        e.getLocalizedMessage()));

Read more details about sessions in Android.

REST

HTTP method

POST

Request URL

https://www.googleapis.com/fitness/v1/users/me/sessions

Request body

{
    "id": identifier,
    "name": sessionName,
    "description": description,
    "startTimeMillis": startTime,
    "endTimeMillis": endTime,
    "version": 1,
    "lastModifiedToken": "exampleToken",
    "application": {
        "detailsUrl": "http://example.com",
        "name": "Foo Example App",
        "version": "1.0"
    },
    "activityType": 72 // Sleep
}

Sleep stages granularity example

To write sleep with stages granularity, write both the top-level sleep session and segments for the different stages of sleep.

Write sleep segments

In this example we will write several segments to represent the several sleep stages over one night of sleep.

Android

DataSource dataSource = new DataSource.Builder()
    .setType(DataSource.TYPE_RAW)
    .setDataType(DataType.TYPE_ACTIVITY_SEGMENT)
    .setAppPackageName(context)
    // Optional but recommended for identifying the stream if you have multiple streams with the same dataType.
    .setStreamName(streamName)
    .build();

DataSet dataSet = DataSet.builder(dataSource)
    .add(
        DataPoint.builder(dataSource)
            .setTimeInterval(startTime1, endTime1, TimeUnit.MILLISECONDS)
            .setField(Field.FIELD_ACTIVITY, FitnessActivities.LIGHT_SLEEP)
            .build())
    .add(
        DataPoint.builder(dataSource)
            .setTimeInterval(startTime2, endTime2, TimeUnit.MILLISECONDS)
            .setField(Field.FIELD_ACTIVITY, FitnessActivities.DEEP_SLEEP)
            .build())
    .add(
        DataPoint.builder(dataSource)
            .setTimeInterval(startTime3, endTime3, TimeUnit.MILLISECONDS)
            .setField(Field.FIELD_ACTIVITY, FitnessActivities.LIGHT_SLEEP)
            .build())
    .add(
        DataPoint.builder(dataSource)
            .setTimeInterval(startTime4, endTime4, TimeUnit.MILLISECONDS)
            .setField(Field.FIELD_ACTIVITY, FitnessActivities.REM_SLEEP)
            .build())
    .add(
        DataPoint.builder(dataSource)
            .setTimeInterval(startTime5, endTime5, TimeUnit.MILLISECONDS)
            .setField(Field.FIELD_ACTIVITY, FitnessActivities.AWAKE)
            .build())
    .add(
        DataPoint.builder(dataSource)
            .setTimeInterval(startTime6, endTime6, TimeUnit.MILLISECONDS)
            .setField(Field.FIELD_ACTIVITY, FitnessActivities.LIGHT_SLEEP)
            .build())
    .build();

REST

  1. First create the dataSource:

    HTTP method

    POST
    

    Request URL

    https://www.googleapis.com/fitness/v1/users/me/datasources
    

    Request body

    {
      "dataStreamName": streamName,
      "type": "raw",
      "application": {
        "detailsUrl": "http://example.com",
        "name": "Foo Example App",
        "version": "1"
      },
      "dataType": {
        "name": "com.google.activity.segment",
        "field": [
          {
            "name": "activity",
            "format": "integer"
          }
        ]
      }
    }
    
  2. Then populate the dataSet:

    HTTP method

    PATCH
    

    Request URL

    https://www.googleapis.com/fitness/v1/users/userId/dataSources/dataSourceId/datasets/datasetId
    

    Request body

    {
        "dataSourceId": dataSourceId,
        "Point": [
            {
                "dataTypeName": "com.google.activity.segment",
                "startTimeMillis": startTime1,
                "endTimeMillis": endTime1,
                "value": [
                    {
                        intVal: 109 // Light sleep
                    }
                ]
            },
            {
                "dataTypeName": "com.google.activity.segment",
                "startTimeMillis": startTime2,
                "endTimeMillis": endTime2,
                "value": [
                    {
                        intVal: 110 // Deep sleep
                    }
                ]
            },
            {
                "dataTypeName": "com.google.activity.segment",
                "startTimeMillis": startTime3,
                "endTimeMillis": endTime3,
                "value": [
                    {
                        intVal: 109 // Light sleep
                    }
                ]
            },
            {
                "dataTypeName": "com.google.activity.segment",
                "startTimeMillis": startTime4,
                "endTimeMillis": endTime4,
                "value": [
                    {
                        intVal: 111 // REM sleep
                    }
                ]
            },
            {
                "dataTypeName": "com.google.activity.segment",
                "startTimeMillis": startTime5,
                "endTimeMillis": endTime5,
                "value": [
                    {
                        intVal: 112 // Awake
                    }
                ]
            },
            {
                "dataTypeName": "com.google.activity.segment",
                "startTimeMillis": startTime6,
                "endTimeMillis": endTime6,
                "value": [
                    {
                        intVal: 109 // Light sleep
                    }
                ]
            }
         ]
     }
    

Write sleep session

Finally, group the segments above by inserting a sleep session. Set the start time for this session to the start time of the first segment, and the end time to the end time of the last segment.

Android

Session session = new Session.Builder()
       .setName(sessionName)
       .setIdentifier(identifier)
       .setDescription(description)
       .setStartTime(startTime1, TimeUnit.MILLISECONDS) // From first segment
       .setEndTime(endTime6, TimeUnit.MILLISECONDS) // From last segment
       .setActivity(FitnessActivities.SLEEP)
       .build();

 SessionInsertRequest request = new SessionInsertRequest.Builder()
       .setSession(session)
       .addDataSet(dataSet)
       .build();

Fitness.getSessionsClient(this, GoogleSignIn.getLastSignedInAccount(this))
       .insertSession(request)
       .addOnSuccessListener(
           unused ->
               // At this point, the session has been inserted and can be read.
               Log.i(TAG, "Session insert was successful!"))
       .addOnFailureListener(
           e ->
               Log.i(TAG, "There was a problem inserting the session: " +
                   e.getLocalizedMessage()));

REST

HTTP method

PATCH

Request URL

https://www.googleapis.com/fitness/v1/users/userId/dataSources/dataSourceId/datasets/datasetId

Request body

{
    "id": identifier,
    "name": sessionName,
    "description": description,
    "startTimeMillis": startTime1,
    "endTimeMillis": endTime6,
    "version": 1,
    "lastModifiedToken": "exampleToken",
    "application": {
        "detailsUrl": "http://example.com",
        "name": "Foo Example App",
        "version": "1.0"
    },
    "activityType": 72 // Sleep
}