> ## Documentation Index
> Fetch the complete documentation index at: https://www.courier.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Update user preferences in bulk

> Additively create or update a user's preferences for one or more subscription topics in a single request. Only the topics included in the request body are created or updated; any existing overrides for topics not listed are left untouched.

Structural validation of the request body fails fast with a single `400`. Beyond that, each topic is processed independently (partial-success, not all-or-nothing): valid topics are written and returned in `items`, while topics that cannot be applied are collected in `errors` with a per-topic `reason` (for example an unknown topic, a `REQUIRED` topic that cannot be opted out, a custom routing request that is not available on the workspace's plan, or a write failure). The request therefore returns `200` with both lists whenever the body is structurally valid.

Every `topic_id` in the response — in both `items` and `errors` — is returned in Courier's canonical topic id form, regardless of the form supplied in the request.



## OpenAPI

````yaml /openapi-specs/openapi.documented.yml post /users/{user_id}/preferences
openapi: 3.0.1
info:
  title: Courier
  description: The Courier REST API for sending and managing notifications across channels.
  version: 0.0.1
servers:
  - url: https://api.courier.com
    description: Production
security: []
paths:
  /users/{user_id}/preferences:
    post:
      tags:
        - User Preferences
      summary: Update user preferences in bulk
      description: >-
        Additively create or update a user's preferences for one or more
        subscription topics in a single request. Only the topics included in the
        request body are created or updated; any existing overrides for topics
        not listed are left untouched.


        Structural validation of the request body fails fast with a single
        `400`. Beyond that, each topic is processed independently
        (partial-success, not all-or-nothing): valid topics are written and
        returned in `items`, while topics that cannot be applied are collected
        in `errors` with a per-topic `reason` (for example an unknown topic, a
        `REQUIRED` topic that cannot be opted out, a custom routing request that
        is not available on the workspace's plan, or a write failure). The
        request therefore returns `200` with both lists whenever the body is
        structurally valid.


        Every `topic_id` in the response — in both `items` and `errors` — is
        returned in Courier's canonical topic id form, regardless of the form
        supplied in the request.
      operationId: users_preferences_bulk_update
      parameters:
        - name: user_id
          in: path
          description: >-
            A unique identifier associated with the user whose preferences you
            wish to update.
          required: true
          schema:
            type: string
          examples:
            Example1:
              value: abc-123
        - name: tenant_id
          in: query
          description: Update the preferences of a user for this specific tenant context.
          required: false
          schema:
            type: string
            nullable: true
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UsersBulkUpdatePreferencesParams'
            examples:
              Example1:
                value:
                  topics:
                    - topic_id: pt_01kx4h2jdafq8bk996nn92357r
                      status: OPTED_IN
                      has_custom_routing: true
                      custom_routing:
                        - inbox
                        - email
                    - topic_id: pt_01kx4h2jdafq8bk99eyt3dx43x
                      status: OPTED_OUT
      responses:
        '200':
          description: >-
            The bulk update was applied. `items` contains the resulting topic
            overrides that were created or updated, and `errors` lists any
            topics that could not be applied, each with a reason.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UsersBulkUpdatePreferencesResponse'
              examples:
                Example1:
                  value:
                    items:
                      - topic_id: pt_01kx4h2jdafq8bk996nn92357r
                        status: OPTED_IN
                        has_custom_routing: true
                        custom_routing:
                          - inbox
                          - email
                    errors:
                      - topic_id: pt_01kx4h2jdafq8bk99eyt3dx43x
                        reason: Topic pt_01kx4h2jdafq8bk99eyt3dx43x not found
        '400':
          description: >-
            The request was malformed and nothing was applied — for example a
            missing or oversized `topics` array, unknown properties, or
            malformed JSON.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BadRequest'
              examples:
                Example:
                  value:
                    message: Example message text
                    type: invalid_request_error
        '429':
          description: Too many requests; the client has been rate limited.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TooManyRequests'
              examples:
                Example:
                  value:
                    message: Too Many Requests
                    type: rate_limit_error
      security:
        - BearerAuth: []
      x-codeSamples:
        - lang: JavaScript
          source: >-
            import Courier from '@trycourier/courier';


            const client = new Courier({
              apiKey: process.env['COURIER_API_KEY'], // This is the default and can be omitted
            });


            const response = await
            client.users.preferences.bulkUpdate('user_id', {
              topics: [
                {
                  topic_id: 'pt_01kx4h2jdafq8bk996nn92357r',
                  status: 'OPTED_IN',
                  has_custom_routing: true,
                  custom_routing: ['inbox', 'email'],
                },
                { topic_id: 'pt_01kx4h2jdafq8bk99eyt3dx43x', status: 'OPTED_OUT' },
              ],
            });


            console.log(response.errors);
        - lang: Python
          source: |-
            import os
            from courier import Courier

            client = Courier(
                api_key=os.environ.get("COURIER_API_KEY"),  # This is the default and can be omitted
            )
            response = client.users.preferences.bulk_update(
                user_id="user_id",
                topics=[{
                    "topic_id": "pt_01kx4h2jdafq8bk996nn92357r",
                    "status": "OPTED_IN",
                    "has_custom_routing": True,
                    "custom_routing": ["inbox", "email"],
                }, {
                    "topic_id": "pt_01kx4h2jdafq8bk99eyt3dx43x",
                    "status": "OPTED_OUT",
                }],
            )
            print(response.errors)
        - lang: Go
          source: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/trycourier/courier-go\"\n\t\"github.com/trycourier/courier-go/option\"\n\t\"github.com/trycourier/courier-go/shared\"\n)\n\nfunc main() {\n\tclient := courier.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tresponse, err := client.Users.Preferences.BulkUpdate(\n\t\tcontext.TODO(),\n\t\t\"user_id\",\n\t\tcourier.UserPreferenceBulkUpdateParams{\n\t\t\tTopics: []courier.UserPreferenceBulkUpdateParamsTopic{{\n\t\t\t\tTopicID:          \"pt_01kx4h2jdafq8bk996nn92357r\",\n\t\t\t\tStatus:           \"OPTED_IN\",\n\t\t\t\tHasCustomRouting: courier.Bool(true),\n\t\t\t\tCustomRouting:    []shared.ChannelClassification{shared.ChannelClassificationInbox, shared.ChannelClassificationEmail},\n\t\t\t}, {\n\t\t\t\tTopicID: \"pt_01kx4h2jdafq8bk99eyt3dx43x\",\n\t\t\t\tStatus:  \"OPTED_OUT\",\n\t\t\t}},\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", response.Errors)\n}\n"
        - lang: Java
          source: >-
            package com.courier.example;


            import com.courier.client.CourierClient;

            import com.courier.client.okhttp.CourierOkHttpClient;

            import
            com.courier.models.users.preferences.PreferenceBulkUpdateParams;

            import
            com.courier.models.users.preferences.PreferenceBulkUpdateResponse;


            public final class Main {
                private Main() {}

                public static void main(String[] args) {
                    CourierClient client = CourierOkHttpClient.fromEnv();

                    PreferenceBulkUpdateParams params = PreferenceBulkUpdateParams.builder()
                        .userId("user_id")
                        .addTopic(PreferenceBulkUpdateParams.Topic.builder()
                            .status(PreferenceBulkUpdateParams.Topic.Status.OPTED_IN)
                            .topicId("pt_01kx4h2jdafq8bk996nn92357r")
                            .build())
                        .addTopic(PreferenceBulkUpdateParams.Topic.builder()
                            .status(PreferenceBulkUpdateParams.Topic.Status.OPTED_OUT)
                            .topicId("pt_01kx4h2jdafq8bk99eyt3dx43x")
                            .build())
                        .build();
                    PreferenceBulkUpdateResponse response = client.users().preferences().bulkUpdate(params);
                }
            }
        - lang: Ruby
          source: |-
            require "courier"

            courier = Courier::Client.new(api_key: "My API Key")

            response = courier.users.preferences.bulk_update(
              "user_id",
              topics: [
                {status: :OPTED_IN, topic_id: "pt_01kx4h2jdafq8bk996nn92357r"},
                {status: :OPTED_OUT, topic_id: "pt_01kx4h2jdafq8bk99eyt3dx43x"}
              ]
            )

            puts(response)
        - lang: PHP
          source: >-
            <?php


            require_once dirname(__DIR__) . '/vendor/autoload.php';


            use Courier\Client;

            use Courier\ChannelClassification;

            use Courier\Core\Exceptions\APIException;


            $client = new Client(apiKey: getenv('COURIER_API_KEY') ?: 'My API
            Key');


            try {
              $response = $client->users->preferences->bulkUpdate(
                'user_id',
                topics: [
                  [
                    'status' => 'OPTED_IN',
                    'topicID' => 'pt_01kx4h2jdafq8bk996nn92357r',
                    'customRouting' => [
                      ChannelClassification::INBOX, ChannelClassification::EMAIL
                    ],
                    'hasCustomRouting' => true,
                  ],
                  [
                    'status' => 'OPTED_OUT',
                    'topicID' => 'pt_01kx4h2jdafq8bk99eyt3dx43x',
                    'customRouting' => [ChannelClassification::DIRECT_MESSAGE],
                    'hasCustomRouting' => true,
                  ],
                ],
                tenantID: 'tenant_id',
              );

              var_dump($response);
            } catch (APIException $e) {
              echo $e->getMessage();
            }
        - lang: C#
          source: >-
            using System;

            using TryCourier;

            using TryCourier.Models;

            using TryCourier.Models.Users.Preferences;


            CourierClient client = new();


            PreferenceBulkUpdateParams parameters = new()

            {
                UserID = "user_id",
                Topics =
                [
                    new()
                    {
                        Status = PreferenceBulkUpdateParamsTopicStatus.OptedIn,
                        TopicID = "pt_01kx4h2jdafq8bk996nn92357r",
                        CustomRouting =
                        [
                            ChannelClassification.Inbox, ChannelClassification.Email
                        ],
                        HasCustomRouting = true,
                    },
                    new()
                    {
                        Status = PreferenceBulkUpdateParamsTopicStatus.OptedOut,
                        TopicID = "pt_01kx4h2jdafq8bk99eyt3dx43x",
                        CustomRouting =
                        [
                            ChannelClassification.DirectMessage
                        ],
                        HasCustomRouting = true,
                    },
                ],
            };


            var response = await
            client.Users.Preferences.BulkUpdate(parameters);


            Console.WriteLine(response);
        - lang: CLI
          source: |-
            courier users:preferences bulk-update \
              --api-key 'My API Key' \
              --user-id user_id \
              --topic '{status: OPTED_IN, topic_id: pt_01kx4h2jdafq8bk996nn92357r}' \
              --topic '{status: OPTED_OUT, topic_id: pt_01kx4h2jdafq8bk99eyt3dx43x}'
components:
  schemas:
    UsersBulkUpdatePreferencesParams:
      title: UsersBulkUpdatePreferencesParams
      type: object
      additionalProperties: false
      properties:
        topics:
          type: array
          items:
            $ref: '#/components/schemas/UsersBulkTopicPreferenceUpdate'
          minItems: 1
          maxItems: 50
          description: >-
            The topics to create or update. Between 1 and 50 topics may be
            provided in a single request.
      required:
        - topics
    UsersBulkUpdatePreferencesResponse:
      title: UsersBulkUpdatePreferencesResponse
      type: object
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/UsersBulkPreferenceTopic'
          description: The topics that were successfully created or updated.
        errors:
          type: array
          items:
            $ref: '#/components/schemas/UsersBulkPreferenceError'
          description: The topics that could not be applied, each with a reason.
      required:
        - items
        - errors
    BadRequest:
      title: BadRequest
      type: object
      properties:
        type:
          type: string
          enum:
            - invalid_request_error
      required:
        - type
      allOf:
        - $ref: '#/components/schemas/BaseError'
    TooManyRequests:
      title: TooManyRequests
      type: object
      properties:
        type:
          type: string
          enum:
            - rate_limit_error
      required:
        - type
      allOf:
        - $ref: '#/components/schemas/BaseError'
    UsersBulkTopicPreferenceUpdate:
      title: UsersBulkTopicPreferenceUpdate
      type: object
      additionalProperties: false
      properties:
        topic_id:
          type: string
          description: A unique identifier associated with a subscription topic.
        status:
          type: string
          description: The subscription status to apply for this topic.
          enum:
            - OPTED_IN
            - OPTED_OUT
        has_custom_routing:
          type: boolean
          description: >-
            Whether the recipient has chosen specific delivery channels for this
            topic.
        custom_routing:
          type: array
          items:
            $ref: '#/components/schemas/ChannelClassification'
          description: >-
            The channels a user has chosen to receive notifications through for
            this topic.
      required:
        - topic_id
        - status
    UsersBulkPreferenceTopic:
      title: UsersBulkPreferenceTopic
      type: object
      description: A single topic override echoed in a bulk preference response.
      properties:
        topic_id:
          type: string
        status:
          type: string
          description: >-
            The applied subscription status. Echoes the requested value, so it
            is always OPTED_IN or OPTED_OUT.
          enum:
            - OPTED_IN
            - OPTED_OUT
        has_custom_routing:
          type: boolean
        custom_routing:
          type: array
          items:
            $ref: '#/components/schemas/ChannelClassification'
      required:
        - topic_id
        - status
        - has_custom_routing
        - custom_routing
    UsersBulkPreferenceError:
      title: UsersBulkPreferenceError
      type: object
      description: A single topic that could not be applied in a bulk preference request.
      properties:
        topic_id:
          type: string
        reason:
          type: string
          description: A human-readable explanation of why the topic could not be applied.
      required:
        - topic_id
        - reason
    BaseError:
      title: BaseError
      type: object
      properties:
        message:
          type: string
          description: A message describing the error that occurred.
      required:
        - message
    ChannelClassification:
      title: ChannelClassification
      type: string
      enum:
        - direct_message
        - email
        - push
        - sms
        - webhook
        - inbox
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer

````