> ## 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.

# Replace user preferences in bulk

> Replace a user's complete set of preference overrides in a single request. The topics in the request body become the recipient's entire set of overrides: listed topics are created or updated, and every existing override that is not included in the body is reset to its topic default. Submitting an empty `topics` array is a valid clear-all that resets every existing override.

This operation is validation-atomic (all-or-nothing): structural validation fails fast with a single `400`, and if any topic is semantically invalid (an unknown topic, a `REQUIRED` topic that cannot be opted out, or a custom routing request that is not available on the workspace's plan) the request returns a single `400` aggregating every failure in `errors` and writes nothing. On success it returns `200` with `items` (the complete resulting override set) and `deleted` (the ids of the overrides that were reset to default).

Every `topic_id` in the response — in `items`, `deleted`, and any `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 put /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:
    put:
      tags:
        - User Preferences
      summary: Replace user preferences in bulk
      description: >-
        Replace a user's complete set of preference overrides in a single
        request. The topics in the request body become the recipient's entire
        set of overrides: listed topics are created or updated, and every
        existing override that is not included in the body is reset to its topic
        default. Submitting an empty `topics` array is a valid clear-all that
        resets every existing override.


        This operation is validation-atomic (all-or-nothing): structural
        validation fails fast with a single `400`, and if any topic is
        semantically invalid (an unknown topic, a `REQUIRED` topic that cannot
        be opted out, or a custom routing request that is not available on the
        workspace's plan) the request returns a single `400` aggregating every
        failure in `errors` and writes nothing. On success it returns `200` with
        `items` (the complete resulting override set) and `deleted` (the ids of
        the overrides that were reset to default).


        Every `topic_id` in the response — in `items`, `deleted`, and any
        `errors` — is returned in Courier's canonical topic id form, regardless
        of the form supplied in the request.
      operationId: users_preferences_bulk_replace
      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: Replace 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/UsersBulkReplacePreferencesParams'
            examples:
              Example1:
                value:
                  topics:
                    - topic_id: pt_01kx4h2jdafq8bk996nn92357r
                      status: OPTED_IN
                      has_custom_routing: true
                      custom_routing:
                        - inbox
                        - email
      responses:
        '200':
          description: >-
            The replacement was applied. `items` contains the complete resulting
            set of topic overrides for the user, and `deleted` lists the ids of
            the overrides that were reset to their topic default.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UsersBulkReplacePreferencesResponse'
              examples:
                Example1:
                  value:
                    items:
                      - topic_id: pt_01kx4h2jdafq8bk996nn92357r
                        status: OPTED_IN
                        has_custom_routing: true
                        custom_routing:
                          - inbox
                          - email
                    deleted:
                      - pt_01kx4h2jdafq8bk99eyt3dx43x
        '400':
          description: >-
            The request was rejected and nothing was applied. Semantic
            validation failures (unknown topic, a REQUIRED topic that cannot be
            opted out, or plan-gated custom routing) are aggregated into
            UsersBulkPreferenceValidationError (with a per-topic errors list).
            Structural failures (missing/oversized topics, unknown properties,
            malformed JSON) return the standard BadRequest shape.
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/UsersBulkPreferenceValidationError'
                  - $ref: '#/components/schemas/BadRequest'
              examples:
                Semantic:
                  value:
                    message: One or more preferences could not be updated
                    errors:
                      - topic_id: pt_01kx4h2jdafq8bk99eyt3dx43x
                        reason: Topic pt_01kx4h2jdafq8bk99eyt3dx43x not found
                Structural:
                  value:
                    message: 'topics: Too big: expected array to have <=50 items'
                    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.bulkReplace('user_id', {
              topics: [
                {
                  topic_id: 'pt_01kx4h2jdafq8bk996nn92357r',
                  status: 'OPTED_IN',
                  has_custom_routing: true,
                  custom_routing: ['inbox', 'email'],
                },
              ],
            });


            console.log(response.deleted);
        - 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_replace(
                user_id="user_id",
                topics=[{
                    "topic_id": "pt_01kx4h2jdafq8bk996nn92357r",
                    "status": "OPTED_IN",
                    "has_custom_routing": True,
                    "custom_routing": ["inbox", "email"],
                }],
            )
            print(response.deleted)
        - 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.BulkReplace(\n\t\tcontext.TODO(),\n\t\t\"user_id\",\n\t\tcourier.UserPreferenceBulkReplaceParams{\n\t\t\tTopics: []courier.UserPreferenceBulkReplaceParamsTopic{{\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},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", response.Deleted)\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.PreferenceBulkReplaceParams;

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


            public final class Main {
                private Main() {}

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

                    PreferenceBulkReplaceParams params = PreferenceBulkReplaceParams.builder()
                        .userId("user_id")
                        .addTopic(PreferenceBulkReplaceParams.Topic.builder()
                            .status(PreferenceBulkReplaceParams.Topic.Status.OPTED_IN)
                            .topicId("pt_01kx4h2jdafq8bk996nn92357r")
                            .build())
                        .build();
                    PreferenceBulkReplaceResponse response = client.users().preferences().bulkReplace(params);
                }
            }
        - lang: Ruby
          source: |-
            require "courier"

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

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

            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->bulkReplace(
                'user_id',
                topics: [
                  [
                    'status' => 'OPTED_IN',
                    'topicID' => 'pt_01kx4h2jdafq8bk996nn92357r',
                    'customRouting' => [
                      ChannelClassification::INBOX, ChannelClassification::EMAIL
                    ],
                    '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();


            PreferenceBulkReplaceParams parameters = new()

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


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


            Console.WriteLine(response);
        - lang: CLI
          source: |-
            courier users:preferences bulk-replace \
              --api-key 'My API Key' \
              --user-id user_id \
              --topic '{status: OPTED_IN, topic_id: pt_01kx4h2jdafq8bk996nn92357r}'
components:
  schemas:
    UsersBulkReplacePreferencesParams:
      title: UsersBulkReplacePreferencesParams
      type: object
      additionalProperties: false
      properties:
        topics:
          type: array
          items:
            $ref: '#/components/schemas/UsersBulkTopicPreferenceUpdate'
          minItems: 0
          maxItems: 50
          description: >-
            The complete set of topic overrides for the user. Up to 50 topics
            may be provided. Any existing override not listed here is reset to
            its topic default; an empty array resets every existing override.
      required:
        - topics
    UsersBulkReplacePreferencesResponse:
      title: UsersBulkReplacePreferencesResponse
      type: object
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/UsersBulkPreferenceTopic'
          description: The complete resulting set of topic overrides for the user.
        deleted:
          type: array
          items:
            type: string
          description: The ids of the overrides that were reset to their topic default.
      required:
        - items
        - deleted
    UsersBulkPreferenceValidationError:
      title: UsersBulkPreferenceValidationError
      type: object
      description: >-
        Returned when a bulk replace request is rejected because one or more
        topics are invalid. No changes are applied.
      properties:
        message:
          type: string
        errors:
          type: array
          items:
            $ref: '#/components/schemas/UsersBulkPreferenceError'
          description: Every topic that failed validation.
      required:
        - message
        - 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

````