> You are reading the Docusign Developer Documentation. For clean Markdown of any page, append .md to the page URL.
>
> Documentation indexes by section:
> - APIs and SDKs: https://docusign.docs.buildwithfern.com/docs/llms.txt
> - Platform 101: https://docusign.docs.buildwithfern.com/platform/llms.txt
> - Extension Apps: https://docusign.docs.buildwithfern.com/extension-apps/llms.txt
> - Docusign CLI: https://docusign.docs.buildwithfern.com/docusign-cli/llms.txt
>
> Authentication (OAuth, JWT Grant, M2M): https://docusign.docs.buildwithfern.com/platform/auth
> Webhooks and Connect: https://docusign.docs.buildwithfern.com/platform/webhooks
>
> OpenAPI specifications: https://docusign.docs.buildwithfern.com/openapi.json
> MCP server: https://docusign.docs.buildwithfern.com/_mcp/server

# How to apply a brand and template to an envelope

> Demonstrates how to apply a brand and a template to an envelope with the eSignature REST API.

This topic demonstrates how to apply a brand and a template to an envelope with the eSignature REST API.

> **Note**
>
> Run this code example from our [Quickstart](/docs/esign-rest-api/quickstart) or launcher projects: [Bash](https://github.com/docusign/code-examples-bash), [C#](https://github.com/docusign/code-examples-csharp), [Java](https://github.com/docusign/code-examples-java), [Node.js](https://github.com/docusign/code-examples-node), [PHP](https://github.com/docusign/code-examples-php), [PowerShell](https://github.com/docusign/code-examples-powershell), [Python](https://github.com/docusign/code-examples-python), or [Ruby](https://github.com/docusign/code-examples-ruby).

## Required data

Running the code in this how-to requires this data:

| Data element      | Description                                                                                                                                                                                                                                                                                                            |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| \{API_ACCOUNT_ID} | A [GUID](http://guid.one/) value that identifies your account. This value is automatically generated by Docusign for any account you create. Copy the value from the **API Account ID** field on the [Apps and Keys](https://admindemo.docusign.com/authenticate?goTo=appsAndKeys) page.                               |
| \{BASE_PATH}      | A string value that forms the root of the URL required to make API calls. The base path value in the example code is set to target the developer environment at https\://\<domain>/restapi Where \<domain> is demo.docusign.net for the developer environment and is the result of the GetUserInfo call in production. |
| \{BRAND_ID}       | A [GUID](http://guid.one/) value that identifies a brand. For more information, see [Branding](/docs/esign-rest-api/esign101/concepts/branding).                                                                                                                                                                       |
| \{SIGNER_EMAIL}   | A string value for the email address where the signer will receive a notification of the signing request.                                                                                                                                                                                                              |
| \{SIGNER_NAME}    | A string value for the full name of the signer.                                                                                                                                                                                                                                                                        |
| \{TEMPLATE_ID}    | A [GUID](http://guid.one/) value that identifies a Docusign [template](/docs/esign-rest-api/esign101/concepts/templates) that is used to create a Docusign [envelope](/docs/esign-rest-api/esign101/concepts/envelopes). This value is automatically generated by Docusign when the template is created.               |

## Step 1. Obtain your OAuth token

To make the API call shown in this how-to, you need a valid OAuth access token. Docusign supports access tokens for three different recommended OAuth grant types: Public Authorization Code Grant, Confidential Authorization Code Grant, and JSON Web Token (JWT) Grant. Choose the OAuth grant type appropriate for your scenario.

> **Note**
>
> See [Confidential Authorization Code Grant](/platform/auth/authcode#confidential-authorization-code-grant) for guidance on your options to get an Confidential Authorization Code Grant  OAuth token.

![Three icons that represent the three methods a user can use to obtain an OAuth token: JSON Web Token (JWT), Public Authorization Code Grant (ACG), and Confidential Authorization Code grant](/_fern-files/_img/64f473773042ee439449a096bf7673292b1585b86a4ccc55f82ba0dda41f61a1.webp)

## Step 2. Construct your API headers

After you have a valid OAuth access token, you are ready to construct the API headers that you will pass to the API call. Construct your headers like this, but make sure to substitute your valid OAuth access token for \{ACCESS_TOKEN}.

**`Bash`**

```bash title="Bash"
declare -a Headers=('--header' "Authorization: Bearer ${ACCESS_TOKEN}" \
					'--header' "Accept: application/json" \
					'--header' "Content-Type: application/json")
```

**`C#`**

```csharp title="C#"
var docuSignClient = new DocuSignClient(basePath);
docuSignClient.Configuration.DefaultHeader.Add("Authorization", "Bearer " + accessToken);
```

**`Java`**

```java title="Java"
ApiClient apiClient = createApiClient(session.getBasePath(), user.getAccessToken());
```

**`Node.js`**

```javascript title="Node.js"
let dsApiClient = new docusign.ApiClient();
dsApiClient.setBasePath(args.basePath);
dsApiClient.addDefaultHeader('Authorization', 'Bearer ' + args.accessToken);
```

**`PHP`**

```php title="PHP"
$config = new Configuration();
$config->setHost($args['base_path']);
$config->addDefaultHeader('Authorization', 'Bearer ' . $args['ds_access_token']);
$this->apiClient = new ApiClient($config);
```

**`PowerShell`**

```text title="PowerShell"
$headers = @{
    'Authorization' = "Bearer $accessToken";
    'Content-Type'  = "application/json";
  }
```

**`Python`**

```python title="Python"
api_client = create_api_client(base_path=args["base_path"], access_token=args["access_token"])
```

**`Ruby`**

```ruby title="Ruby"
configuration = DocuSign_eSign::Configuration.new
configuration.host = args[:base_path]
api_client = DocuSign_eSign::ApiClient.new configuration

api_client.default_headers['Authorization'] = "Bearer #{args[:access_token]}"
```

## Step 3. Construct the request body

Next, create the request body to create an envelope using your template and brand, substituting your signer email for \{SIGNER_EMAIL}, signer name for \{SIGNER_NAME}, template ID for \{TEMPLATE_ID] and your brand ID for \{BRAND_ID}.

**`Bash`**

```bash title="Bash"
printf \
'{
    "templateId": "'$template_id'",
    "brandId": "'$brand_id'",
    "templateRoles": [
        {
            "email": "'"${SIGNER_EMAIL}"'",
            "name": "'"${SIGNER_NAME}"'",
            "roleName": "signer"
        },
        {
            "email": "'"${CC_EMAIL}"'",
            "name": "'"${CC_NAME}"'",
            "roleName": "cc"
        }
    ],
        "status": "sent"
}' >> $request_data
```

**`C#`**

```csharp title="C#"
EnvelopeDefinition envelopeDefinition = new EnvelopeDefinition
{
    TemplateId = templateId,
    BrandId = brandId,
    TemplateRoles = new List<TemplateRole>
    {
        new TemplateRole
        {
            Name = signerName,
            Email = signerEmail,
            RoleName = "signer",
        },
        new TemplateRole
        {
            Name = ccName,
            Email = ccEmail,
            RoleName = "cc",
        },
    },
    Status = status,
};
```

**`Java`**

```java title="Java"
private static EnvelopeDefinition makeEnvelope(WorkArguments args, String templateId) {
    TemplateRole signer = new TemplateRole()
            .email(args.getSignerEmail())
            .name(args.getSignerName())
            .roleName(EnvelopeHelpers.SIGNER_ROLE_NAME);

    TemplateRole cc = new TemplateRole()
            .email(args.getCcEmail())
            .name(args.getCcName())
            .roleName(EnvelopeHelpers.CC_ROLE_NAME);

    return new EnvelopeDefinition()
            .templateId(templateId)
            .templateRoles(Arrays.asList(signer, cc))
            .brandId(args.getBrandId())
            .status(EnvelopeHelpers.ENVELOPE_STATUS_SENT);
}
```

**`Node.js`**

```javascript title="Node.js"
const envDef = {
  envelopeDefinition: {
    templateId: args.templateId,
    brandId: args.brandId,
    templateRoles: args.templateRoles,
    status: 'sent',
  },
};
```

**`PHP`**

```php title="PHP"
$envelope_definition = ApplyBrandToTemplateService::makeEnvelope($args["envelope_args"]);
    public static function makeEnvelope(array $args): EnvelopeDefinition
    {
$signer = new TemplateRole([
    'name' => $args['signer_name'],
    'email' => $args['signer_email'],
    'role_name' => 'signer'
]);
$cc = new TemplateRole([
        'name' => $args['cc_name'],
        'email' => $args['cc_email'],
        'role_name' => 'cc'
]);
# Next, create the top-level envelope definition and populate it
return new EnvelopeDefinition([
    'template_id' => $args['template_id'],
    'template_roles' => [$signer, $cc],
    'status' => "sent", # Request that the envelope be created and sent
    'brand_id' => $args["brand_id"], # Apply selected Brand to envelope
]);
    }
```

**`PowerShell`**

```text title="PowerShell"
$body = @"
    {
        "templateId": "${templateID}",
        "brandId": "${brandId}",
        "templateRoles": [
            {
                "email": "${SIGNER_EMAIL}",
                "name": "${SIGNER_NAME}",
                "roleName": "signer"
            },
            {
                "email": "${CC_EMAIL}",
                "name": "${CC_NAME}",
                "roleName": "cc"
            }
        ],
        "status": "sent"
    }
"@
```

**`Python`**

```python title="Python"
envelope_definition = cls.make_envelope(args["envelope_args"])
    def make_envelope(cls, args):
"""
Creates the envelope definition object
"""
# Create the envelope definition
envelope_definition = EnvelopeDefinition(
    status="sent",
    template_id=args["template_id"],
    brand_id=args["brand_id"]
)

signer = TemplateRole(
    email=args["signer_email"],
    name=args["signer_name"],
    role_name="signer"
)

# In case, we have cc we add him to envelope definition
if args["cc_email"] and args["cc_name"]:
    cc = TemplateRole(
        email=args["cc_email"],
        name=args["cc_name"],
        role_name="cc"
    )

    envelope_definition.template_roles = [signer, cc]

else:
    envelope_definition.template_roles = [signer]

return envelope_definition
```

**`Ruby`**

```ruby title="Ruby"
envelope_definition = make_envelope(args[:envelope_args])
  def make_envelope(envelope_args)
# Create the envelope definition with the template_id
envelope_definition = DocuSign_eSign::EnvelopeDefinition.new
# envelope_definition.envelope_id_stamping = true
envelope_definition.template_id = envelope_args[:template_id]
envelope_definition.brand_id = envelope_args[:brand_id]
envelope_definition.status = envelope_args[:status]
# Create the template role elements to connect the signer and cc recipients
# to the template
signer = DocuSign_eSign::TemplateRole.new({
                                            email: envelope_args[:signer_email],
                                            name: envelope_args[:signer_name],
                                            roleName: 'signer'
                                          })
# Create a cc template role
cc = DocuSign_eSign::TemplateRole.new({
                                        email: envelope_args[:cc_email],
                                        name: envelope_args[:cc_name],
                                        roleName: 'cc'
                                      })

envelope_definition.template_roles = [signer, cc]
envelope_definition
  end
```

## Step 4. Call the eSignature REST API

Now that you have constructed your API headers and request body, you can send the envelope with the [Envelopes:create](/docs/esign-rest-api/reference/envelopes/envelopes/create) method and include the request body to generate the envelope from your template and customized by your brand. Here’s how you make the call, but make sure to substitute your API account ID for \{ACCOUNT_ID}, your brand ID for \{BRAND_ID}, and your template ID for \{TEMPLATE_ID}.

> **Note**
>
> View the source code for this how-to on GitHub: [Bash](https://github.com/docusign/code-examples-bash/blob/master/examples/eSignature/eg030ApplyingBrandTemplate.sh), [C#](https://github.com/docusign/code-examples-csharp/blob/master/launcher-csharp/eSignature/Examples/ApplyBrandToTemplate.cs), [Java](https://github.com/docusign/code-examples-java/blob/master/src/main/java/com/docusign/controller/eSignature/services/ApplyBrandToTemplateService.java), [Node.js](https://github.com/docusign/code-examples-node/blob/master/lib/eSignature/examples/applyBrandToTemplate.js), [PHP](https://github.com/docusign/code-examples-php/blob/master/src/Services/Examples/eSignature/ApplyBrandToTemplateService.php), [PowerShell](https://github.com/docusign/code-examples-powerShell/blob/master/examples/eSignature/eg030ApplyingBrandTemplate.ps1), [Python](https://github.com/docusign/code-examples-python/blob/master/app/eSignature/examples/eg030_brands_apply_to_template.py), or [Ruby](https://github.com/docusign/code-examples-ruby/blob/main/app/services/e_sign/eg030_brands_apply_to_template_service.rb).

**`Bash`**

```bash title="Bash"
Status=$(curl -w '%{http_code}' -i --request POST ${base_path}/v2.1/accounts/${account_id}/envelopes \
     "${Headers[@]}" \
     --data-binary @${request_data} \
     --output ${response})
```

**`C#`**

```csharp title="C#"
var response = envelopesApi.CreateEnvelopeWithHttpInfo(accountId, envelopeDefinition);

response.Headers.TryGetValue("X-RateLimit-Remaining", out string remaining);
response.Headers.TryGetValue("X-RateLimit-Reset", out string reset);

if (reset != null && remaining != null)
{
    DateTime resetDate = DateTimeOffset.FromUnixTimeSeconds(long.Parse(reset)).UtcDateTime;
    Console.WriteLine("API calls remaining: " + remaining);
    Console.WriteLine("Next Reset: " + resetDate);
}

return response.Data;
```

**`Java`**

```java title="Java"
		var createEnvelopeResponse = envelopesApi.createEnvelopeWithHttpInfo(accountId, envelope,
				envelopesApi.new CreateEnvelopeOptions());
		Map<String, List<String>> headers = createEnvelopeResponse.getHeaders();
		java.util.List<String> remaining = headers.get("X-RateLimit-Remaining");
		List<String> reset = headers.get("X-RateLimit-Reset");

		if (remaining != null & reset != null) {
			Instant resetInstant = Instant.ofEpochSecond(Long.parseLong(reset.get(0)));
			System.out.println("API calls remaining: " + remaining);
			System.out.println("Next Reset: " + resetInstant);
		}

		return createEnvelopeResponse.getData();
```

**`Node.js`**

```javascript title="Node.js"
let results = await envelopesApi.createEnvelope(args.accountId, envDef, (error, data, response) => {
    const headers = response?.headers;

    const remaining = headers?.['x-ratelimit-remaining'];
    const reset = headers?.['x-ratelimit-reset'];

    if (remaining && reset) {
      const resetInstant = new Date(Number(reset) * 1000);

      console.log(`API calls remaining: ${remaining}`);
      console.log(`Next Reset: ${resetInstant.toISOString()}`);
    }
});
```

**`PHP`**

```php title="PHP"
$envelope_api = $clientService->getEnvelopeApi();
$createdEnvelope = $envelope_api->createEnvelopeWithHttpInfo(
    $args['account_id'],
    $envelope_definition
);

$remaining = $createdEnvelope[2]['X-RateLimit-Remaining'] ?? null;
$reset = $createdEnvelope[2]['X-RateLimit-Reset'] ?? null;

if ($remaining !== null && $reset !== null) {
    $resetInstant = (new DateTime())->setTimestamp((int)$reset);
    error_log("API calls remaining: $remaining");
    error_log("Next Reset: " . $resetInstant->format(\DateTime::ATOM));
}
```

**`PowerShell`**

```text title="PowerShell"
$uri = "https://demo.docusign.net/restapi/v2.1/accounts/$APIAccountId/envelopes"

try {
    Write-Output "Response:"
    $result = Invoke-WebRequest -uri $uri -headers $headers -body $body -method POST
    $result.content | ConvertFrom-Json | ConvertTo-Json
}
catch {
    $int = 0
    foreach ($header in $_.Exception.Response.Headers) {
        if ($header -eq "X-DocuSign-TraceToken") { Write-Output "TraceToken : " $_.Exception.Response.Headers[$int] }
        $int++
    }
    Write-Output "Error : "$_.ErrorDetails.Message
    Write-Output "Command : "$_.InvocationInfo.Line
}
```

**`Python`**

```python title="Python"
(response, status, headers) = envelope_api.create_envelope_with_http_info(account_id=args["account_id"], envelope_definition=envelope_definition)

remaining = headers.get("X-RateLimit-Remaining")
reset = headers.get("X-RateLimit-Reset")

if remaining is not None and reset is not None:
    reset_date = dt.fromtimestamp(int(reset), tz=timezone.utc)
    print(f"API calls remaining: {remaining}")
    print(f"Next Reset: {reset_date}")
```

**`Ruby`**

```ruby title="Ruby"
results, _status, headers = envelope_api.create_envelope_with_http_info args[:account_id], envelope_definition

remaining = headers['X-RateLimit-Remaining']
reset = headers['X-RateLimit-Reset']

if remaining && reset
  reset_date = Time.at(reset.to_i).utc
  puts "API calls remaining: #{remaining}"
  puts "Next Reset: #{reset_date}"
end
```

## Expected response

If you run this code example from our Quickstart or launcher projects, you should see a JSON response similar to the code shown.

**`Sample response`**

```json title="Sample response"
{
  "envelopeId": "e2b719ff-xxxx-xxxx-xxxx-a2dfc235fd09",
  "uri": "/envelopes/e2b719ff-xxxx-xxxx-xxxx-a2dfc235fd09",
  "statusDateTime": "2020-08-12T23:23:19.9200000Z",
  "status": "sent"
}
```

## Next steps

* Run this code example from our [Quickstart](/docs/esign-rest-api/quickstart) or launcher projects:    [Bash](https://github.com/docusign/code-examples-bash), [C#](https://github.com/docusign/code-examples-csharp), [Java](https://github.com/docusign/code-examples-java), [Node.js](https://github.com/docusign/code-examples-node), [PHP](https://github.com/docusign/code-examples-php), [PowerShell](https://github.com/docusign/code-examples-powershell), [Python](https://github.com/docusign/code-examples-python), or [Ruby](https://github.com/docusign/code-examples-ruby).
* Learn more about [branding](/docs/esign-rest-api/esign101/concepts/branding).
* Learn about [creating and using templates](/docs/esign-rest-api/esign101/concepts/templates/creating).
* Review [Working with Templates](https://support.docusign.com/s/document-item?bundleId=xry1643227563338\&topicId=dqj1578456412286.html\&rsc_301) on Docusign Support.
* See how to [Go-Live](/docs/esign-rest-api/go-live) with a completed app and find the base path for API calls in the production environment.