Activities

“In its simplest form, an activity consists of an actor, a verb, and an object. It tells the story of a person performing an action on or with an object.”

Activity Streams Specification 1.0

Adding Activities: Basic

Adding an activity in its simplest form means passing an object with the following basic properties:

  • Actor

  • Verb

  • Object

  • Recommended:

  • Foreign Id

  • Time

Here’s an example:

“Erik is pinning Hawaii to his Places to Visit board.”

Let’s break the example down:

  • Actor : “Eric” (User:1)

  • Verb : “pin”

  • Object : “Hawaii” (Place:42)

  • Foreign Id : “Eric’s board activity” (Activity:1)

  • Time : 2017-07-01T20:30:45.123

As seen above time doesn’t have any timezone information but it’s always in UTC.

Now, let’s show you how to add an activity to a feed using your Stream API client:

// Instantiate a feed object
	userFeed, err := client.FlatFeed("user", "1")
	if err != nil {
		panic(err)
	}

	// Add an activity to the feed, where actor, object and verb are references to objects (`Eric`, `Hawaii`, `Places to Visit`)
	activity := stream.Activity{
		Actor: "User:1",
		Verb:  "pin",
		Object: "Place:42",
	}
	_, err := userFeed.AddActivity(context.TODO(), activity)
	if err != nil {
		panic(err)
	}

Listed below are the mandatory and recommended fields when adding Activities.

Fields

nametypedescriptiondefaultoptional
actorstringthe actor performing the activity-
verbstringThe verb of the activity with a maximum length of 255 bytes-
objectstringThe object of the activity-
timestringThe time of the activity, iso format (UTC local time). Required to ensure activity uniqueness and also to later update activities by Time + Foreign IDCurrent time
tolistSee the documentation on Targeting & “TO” support.-
foreign_idstringA unique ID from your application for this activity. IE: pin:1 or like:300. Required to later update activities by Time + Foreign ID.-
*string / list / object / pointAdd as many custom fields as needed.-

Custom Fields

// Create a bit more complex activity
	activity := stream.Activity{
		Actor:   "User:1",
		Verb:   "run",
		Object:  "Exercise:42",
		ForeignID: "run:1",
		Extra: map[string]any{
			"course": map[string]any{
				"name":   "Golden Gate park",
				"distance": 10,
			},
			"participants": []string{
				"Thierry",
				"Tommaso",
			},
			"started_at": time.Now(),
		},
	}
	_, err := userFeed.AddActivity(context.TODO(), activity)
	if err != nil {
		panic(err)
	}

In the above example, the course, location, participants and started_at fields will be stored with the Activity and included whenever the Activity is retrieved.

For performance reasons, activities are limited in size (10KB) and must not contain blob/binary data (e.g. base64 encoded images). Use references and identifiers to facilitate Activity enrichment by your backend or client.

These reserved words must not be used as field names: activity_id, activity, analytics, extra_context, id, is_read, is_seen, origin, score, site_id, to.

In one add call, at max 100 activities can be included.

Foreign IDs

The example above also specified a foreign_id.

The foreign id is a unique identifier for the activity that can be stored and used within the app. Making use of the the foreign id field is highly recommended as it is needed in order to update Activities.

Add Activity Response Data

When an activity is successfully added, the Stream API includes activity id in the serialized JSON response, like so:

{
  "id": "ef696c12-69ab-11e4-8080-80003644b625",
  "actor": "User:1",
  "course": {
    "distance": 10,
    "name": "Golden Gate Park"
  },
  "object": "Exercise:42",
  "participants": ["Thierry", "Tommaso"],
  "started_at": "2014-11-11T15:06:16+01:00",
  "target": null,
  "time": "2014-11-11T14:06:30.494",
  "verb": "run"
}

Retrieving Activities

The example below shows how to retrieve the Activities in a feed:

// Get activities f


 rom 5 to 10
	resp, err := userFeed.GetActivities(
		context.TODO(),
		stream.WithActivitiesLimit(5),
		stream.WithActivitiesOffset(5),
	)
	if err != nil {
		panic(err)
	}

	// Get the 5 activities added after lastActivity
	resp, err = userFeed.GetActivities(
		context.TODO(),
		stream.WithActivitiesLimit(5),
		stream.WithActivitiesIDLT(lastActivity.ID),
	)
	if err != nil {
		panic(err)
	}

	// Get activities sorted by rank (Ranked Feeds Enabled):
	resp, err = userFeed.GetActivitiesWithRanking(
		context.TODO(),
		"popularity",
		stream.WithActivitiesLimit(5),
	)
	if err != nil {
		panic(err)
	}

Parameters

nametypedescriptiondefaultoptional
limitintegerThe number of Activities to retrieve (max: 100)25
id_gtestringFilter the feed on ids greater than or equal to the given value-
id_gtstringFilter the feed on ids greater than the given value-
id_ltestringFilter the feed on ids smaller than or equal to the given value-
id_ltstringFilter the feed on ids smaller than the given value-
offsetintegerThe offset0
rankingstringThe custom ranking formula used to sort the feed, must be defined in the dashboard-
enrichbooleanWhen using collections, you can request Stream to enrich activities to include themfalse
reactions.ownbooleanInclude reactions added by current user to all activities (see reaction docs)false
reactions.recentbooleanInclude recent reactions to activities (see reaction docs)false
reaction.countsbooleanInclude reaction counts to activities (see reaction docs)false
reaction.kindsarrayFilter reactions with given kinds (support differs by SDKs, request if missing)-

Activity reads returns at most 100 Activities. Requests with a limit greater than 100 are automatically capped.

The maximum depth of activities that can be retrived is 1000

Pagination

The recommended way to paginate feeds is with offset and limit parameters. Such approach makes for simpler code and it works for all types of feeds.

When using id_lte to paginate an aggregated feed, use the ID of the group that is returned from the API. Using an ID of an individual activity within the group will not work and result in an error.

Sorting using a custom ranking formula is only available on paid plans.

While paginating, view is cached to have a consistent scrolling. If you want fresh updated page, pass refresh=true query parameter into feed read call.

Retrieve Feed Response Data

When a feed is successfully retrieved, the Stream API returns the following payload:

{
 results: [],
 next: '/api/v1.0/feed/<< feed_group >>/<< feed_id >>/?api_key=<< api_key >>&id_lt=<< next_activity_id >>&limit=<< activity_limit >>'
}

The format for results array depends on the type of feed associated with the notification. When a Flat Feed is retrieved, the array contains Activities. Whereas when an Aggregated or Notification Feed is retrieved, the array contains Activity Groups.

The ‘next’ property in the response contains a URL that may be used to retrieve the next page of activities within the feed.

Removing Activities

There are two ways to remove an activity:

  • Activity Id - found in the serialized response from server

  • Foreign Id - optionally specified when adding an activity

Have a look at the section on Using Foreign IDs.

// Remove an activity by its id
	_, err := userFeed.RemoveActivityByID(context.TODO(), "e561de8f-00f1-11e4-b400-0cc47a024be0")
	if err != nil {
		panic(err)
	}
	// Remove activities with foreign_id 'run:1'
	_, err = userFeed.RemoveActivityByForeignID(context.TODO(), "run:1")
	if err != nil {
		panic(err)
	}

When you remove by foreign_id field, all activities in the feed with the provided foreign_id will be removed.

Updating Activities

Activities that have both foreign_id and time defined can be updated via the APIs. Changes to activities immediately show up on every feed.

activity := stream.Activity{
		Actor:   "User:1",
		Verb:   "like",
		Object:  "Object:3",
		Time:   stream.Time{time.Now()},
		ForeignID: "like:3",
		Extra: map[string]any{
			"popularity": 100,
		},
	}

	// first time the activity is added
	_, err := userFeed.AddActivity(context.TODO(), activity)
	if err != nil {
		panic(err)
	}

	// update the popularity value for the activity
	activity.Extra["popularity"] = 10

	// send the update to the APIs
	_, err = client.UpdateActivities(context.TODO(), activity)
	if err != nil {
		panic(err)
	}

When you update an activity, you must include the following fields both when adding and updating the activity: time & foreign_id

updateActivities can only be used server-side.

It is not possible to update more than 100 activities per request with this method.

When updating an activity, any changes to the to field are ignored.

This API method works particularly well in combination with the ranked feeds. You can, for instance, issue an update if an activity is promoted or not and use the ranked feeds to show it higher in the feed. Similarly, you could update the like and comment counts and use a ranking method based on popularity to sort the activities.

Activity Partial Update

It is possible to update only a part of an activity with the partial update request. You can think of it as a quick “patching operation”.

The activity to update can be selected by its ID or Foreign ID and Time combination.

A set and an unset params can be provided to add, modify, or remove attributes to/from the target activity. The set and unset params can be used separately or combined together (see below).

// partial update by activity ID

	// prepare the set operations
	set := map[string]any{
		"product.price": 19.99,
		"shares": map[string]any{
			"facebook": "...",
			"twitter": "...",
		},
	}
	// prepare the unset operations
	unset := []string{"daily_likes", "popularity"}

	id := "54a60c1e-4ee3-494b-a1e3-50c06acb5ed4"
	_, err := client.UpdateActivityByID(context.TODO(), id, set, unset)
	if err != nil {
		panic(err)
	}

	// partial update by foreign ID
	foreignID := "product:123"
	timestamp := stream.Time{ /*...*/ }
	_, err := client.UpdateActivityByForeignID(context.TODO(), foreignID, timestamp, set, unset)
	if err != nil {
		panic(err)
	}

Parameters

nametypedescriptiondefaultoptional
idstringThe target activity ID-
foreign_idstringThe target activity foreign ID-
timestringThe target activity timestamp-
setobjectThe set operations, max 25 top level keys-
unsetlistThe unset operations. max 25-

The set object contains the insertion updates for the target fields, where the keys are the activity fields to update and the values are the new ones to assign. If the target field does not exist, it’s created with the given content. If the target field exists, its content is replaced.

It is possible to quickly reference nested elements using the dotted notation ( father.child. ... ), but in this case the whole hierarchy is required to exist and to be valid.

For example, if the target activity looks like the following:

{
  "id": "...", "actor": "...", "object": "...", "verb": "...", "foreign_id": "...",
  "product": {
    "sku": 12345,
    "price": {
      "eur": 7.99,
      "usd": 9.99
    },
    "name": "shoes",
    "popularity": 9000
  }
}

It is possible to update the product’s EUR price with the key "product.price.eur", or even create a new field with the key "product.price.gbp", but it’s not possible to reference a non-existing hierarchy like "product.colors.blue".

The unset field contains a list of key strings that will be removed from the activity’s payload. They must exist, and, if referenced with the dotted notation, their hierarchy must be valid.

The set and unset fields can be combined in the same request, but they must not be conflicting with each other (they must not have operations referencing the same keys or hierarchies).

The following example shows a valid combination of set and unset operations which will update the above example activity:

{
  "set": {
    "product.price.eur": 8.99,
    "product.price.gbp": 6.99,
    "product.available": {
      "blue": 100,
      "black": 300
    },
    "facebook_page": "..."
  },
  "unset": [
    "product.price.usd",
    "popularity"
  ]
}

Note: it is not possible to include the following reserved fields in a partial update request (set or unset): id, actor, verb, object, time, target, foreign_id, to, origin

The size of an activity’s payload must be less than 10KB after all set and unset operations are applied. The size is based on the size of the JSON-encoded activity.

activityPartialUpdate can only be used server-side.

Batching Partial Updates

It is also possible to partially update activities in batches. The same individual activity restrictions are applied, and there’s a limit of 100 activities per batch.

Activities in each batch can be identified either by their ID or by the ForeignID and Time combination:

changesetA := stream.NewUpdateActivityRequestByID(
		"907a8010-1d84-11e9-9457-9cb6d0925edd",
		map[string]any{
			"key": "new-value",
		},
		[]string{"removed", "keys"},
	)
	changesetB := stream.NewUpdateActivityRequestByID(
		"de88ed3c-1d98-11e9-9457-9cb6d0925edd",
		map[string]any{
			"foo": "bar",
			"baz": "quux",
		},
		[]string{"removed", "keys"},
	)
	changesetC := stream.NewUpdateActivityRequestByForeignID(
		"stroll:1",
		stream.Time{ /*...*/ },
		map[string]any{
			"key": "new-value",
		},
		[]string{"removed", "keys"},
	)
	changesetD := stream.NewUpdateActivityRequestByForeignID(
		"stroll:2",
		stream.Time{ /*...*/ },
		map[string]any{
			"foo": "bar",
			"baz": "quux",
		},
		[]string{"removed", "keys"},
	)
	_, err := client.PartialUpdateActivities(context.TODO(), changesetA, changesetB)
	if err != nil {
		panic(err)
	}
	_, err := client.PartialUpdateActivities(context.TODO(), changesetC, changesetD)
	if err != nil {
		panic(err)
	}

Uniqueness & Foreign IDs

Stream handles uniqueness based on the foreign_id and time fields. If you want to be able to update your activities you need to specify both of these fields.

Uniqueness is enforced on the combination of time and foreign_id. See the example below for an overview:

now := time.Now()
	firstActivity, err := userFeed.AddActivity(context.TODO(), stream.Activity{
		Actor:   "1",
		Verb:   "like",
		Object:  "3",
		Time:   stream.Time{now},
		ForeignID: "like:3",
	})
	if err != nil {
		panic(err)
	}
	secondActivity, err := userFeed.AddActivity(context.TODO(), stream.Activity{
		Actor: "1",
		Verb:  "like",
		Object: "3",
		Time:  stream.Time{now},
		Extra: map[string]interface{}{
			"extra": "extra_value",
		},
		ForeignID: "like:3",
	})
	if err != nil {
		panic(err)
	}
	// foreign ID and time are the same for both activities
	// hence only one activity is created and first and second IDs are equal
	// firstActivity.ID == secondActivity.ID

The unique combination of foreign_id and time ensure that both activities are unique and therefore the first_activity_id != second_activity_id.

By default, activity upsert by this uniqueness guarantee is enabled and it can be disabled per application in the server side by contacting to support. Additionally, it’s also disabled if a request is using a client side authentication or has disable_activity_upsert query parameter.

GDPR-compliant actor discarding

Since the Feeds API doesn’t require users there’s no user-to-user blocking. However, in order to stay GDPR compliant there’s support for discarding actors when reading a feed. This leaves it up to the customer to keep track of which users have blocked other users.

# userA has blocked userB and userC
feed = client.feed("user", "userA")
results = feed.get(discard_actors=",".join(["userB", "userC"]))

This a recent feature, if your SDK of choice is not listed please contact support

Automatic Activity Hiding

It’s possible to have the Feeds API automatically hide activities older than X days/months/years. This is an app-level setting, please contact support if you wish to have it enabled.

© Getstream.io, Inc. All Rights Reserved.