> 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 request a signature using a composite template

> Demonstrates how to request a signature via your app, using an envelope derived from multiple templates

This topic demonstrates how to request a signature through your app using a template and an additional, dynamically-constructed HTML document by using the [composite template](/docs/esign-rest-api/esign101/concepts/templates/composite) feature.

> **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. |
| \{CC_RECIPIENT_EMAIL} | A string value for the email address of the carbon copy recipient.                                                                                                                                                                                                                                                     |
| \{CC_RECIPIENT_NAME}  | A string value for the name of the carbon copy recipient.                                                                                                                                                                                                                                                              |
| \{CLIENT_USER_ID}     | A string value that serves as an identifier of an individual signer throughout the signing process. The combination of this value, the signer's name, and the signer's email is used to uniquely identify them.                                                                                                        |
| \{ITEM}               | An arbitrary string used to specify an item being ordered in the document.                                                                                                                                                                                                                                             |
| \{QUANTITY}           | An arbitrary string used to specify a quantity of items being ordered in the document.                                                                                                                                                                                                                                 |
| Redirect URI          | A URL to which the user will be forwarded after authentication. The value for this URL must exactly match one of those pre-registered for the [integration key](/platform/configure-app#integration-key) in your Docusign account. See [redirect URI](/platform/configure-app#redirect-uri) for details.               |
| \{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 calls 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. Create the envelope definition as a part of the composite template

First, create a new envelope definition that declares a pair of `compositeTemplate` objects. Each of these objects will represent one template that you will use to derive the created envelope. The first of these composite templates will be derived from one of your existing templates, specified by its template ID. It is divided into a `serverTemplate` (which holds server-side template data, such as ordering) and an `inlineTemplate` (which holds inline template data, such as tabs/fields). The second composite template will contain the HTML document, as well as its tabs and recipients.

**Note:** When you create an envelope by using a composite template, you should specify the envelope custom fields in the inline template. Any custom fields that you specify at the root level are ignored.

The code for this step demonstrates how to define a method, `makeEnvelope`, that creates an envelope definition using composite templates:

**`Bash`**

```bash title="Bash"
printf \
'{
    "compositeTemplates": [
        {
            "compositeTemplateId": "1",
            "inlineTemplates": [
                {
                    "recipients": {
                        "carbonCopies": [
                            {
                                "email": "'"${CC_EMAIL}"'",
                                "name": "'"${CC_NAME}"'",
                                "recipientId": "2",
                                "roleName": "cc"
                            }
                        ],
                        "signers": [
                            {
                                "clientUserId": "1000",
                                "email": "'"${SIGNER_EMAIL}"'",
                                "name": "'"${SIGNER_NAME}"'",
                                "recipientId": "1",
                                "roleName": "signer"
                            }
                        ]
                    },
                    "sequence": "2"
                }
            ],
            "serverTemplates": [
                {
                    "sequence": "1",
                    "templateId": "' > $request_data
                    printf "${template_id}" >> $request_data
                    printf '"
                }
            ]
        },
        {
            "compositeTemplateId": "2",
            "document": {
                "documentBase64": "' >> $request_data
                cat $doc1_base64 >> $request_data
                printf '",
                "documentId": "1",
                "fileExtension": "html",
                "name": "Appendix 1--Sales order"
            },
            "inlineTemplates": [
                {
                    "recipients": {
                        "carbonCopies": [
                            {
                                "email": "'${CC_EMAIL}'",
                                "name": "'"${CC_NAME}"'",
                                "recipientId": "2",
                                "roleName": "cc"
                            }
                        ],
                        "signers": [
                            {
                                "email": "'"${SIGNER_EMAIL}"'",
                                "name": "'"${SIGNER_NAME}"'",
                                "recipientId": "1",
                                "roleName": "signer",
                                "tabs": {
                                    "signHereTabs": [
                                        {
                                            "anchorString": "**signature_1**",
                                            "anchorUnits": "pixels",
                                            "anchorXOffset": "20",
                                            "anchorYOffset": "10"
                                        }
                                    ]
                                }
                            }
                        ]
                    },
                    "sequence": "1"
                }
            ]
        }
    ],
    "status": "sent"
}' >> $request_data
```

**`C#`**

```csharp title="C#"
public static EnvelopeDefinition MakeEnvelope(
    string signerEmail,
    string signerName,
    string ccEmail,
    string ccName,
    string item,
    string quantity,
    string signerClientId,
    string templateId)
{
    // Data for this method
    // signerEmail
    // signerName
    // ccEmail
    // ccName
    // item
    // quantity
    // signerClientId -- class global

    // The envelope request object uses Composite Template to
    // include in the envelope:
    // 1. A template stored on the DocuSign service
    // 2. An additional document which is a custom HTML source document

    // Create Recipients for server template. Note that Recipients object
    // is used, not TemplateRole
    //
    // Create a signer recipient for the signer role of the server template
    Signer signer1 = new Signer
    {
        Email = signerEmail,
        Name = signerName,
        RoleName = "signer",
        RecipientId = "1",

        // Adding clientUserId transforms the template recipient
        // into an embedded recipient:
        ClientUserId = signerClientId,
    };

    // Create the cc recipient
    CarbonCopy cc1 = new CarbonCopy
    {
        Email = ccEmail,
        Name = ccName,
        RoleName = "cc",
        RecipientId = "2",
    };

    // Recipients object:
    Recipients recipientsServerTemplate = new Recipients
    {
        CarbonCopies = new List<CarbonCopy> { cc1 },
        Signers = new List<Signer> { signer1 },
    };

    // create a composite template for the Server Template
    CompositeTemplate compTemplate1 = new CompositeTemplate
    {
        CompositeTemplateId = "1",
    };
    ServerTemplate serverTemplates = new ServerTemplate
    {
        Sequence = "1",
        TemplateId = templateId,
    };

    compTemplate1.ServerTemplates = new List<ServerTemplate> { serverTemplates };

    // Add the roles via an inlineTemplate
    InlineTemplate inlineTemplate = new InlineTemplate
    {
        Sequence = "2",
        Recipients = recipientsServerTemplate,
    };
    compTemplate1.InlineTemplates = new List<InlineTemplate> { inlineTemplate };

    // The signer recipient for the added document with
    // a tab definition:
    SignHere signHere1 = new SignHere
    {
        AnchorString = "**signature_1**",
        AnchorYOffset = "10",
        AnchorUnits = "pixels",
        AnchorXOffset = "20",
    };

    Tabs signer1Tabs = new Tabs
    {
        SignHereTabs = new List<SignHere> { signHere1 },
    };

    // Signer definition for the added document
    Signer signer1AddedDoc = new Signer
    {
        Email = signerEmail,
        Name = signerName,
        ClientUserId = signerClientId,
        RoleName = "signer",
        RecipientId = "1",
        Tabs = signer1Tabs,
    };

    // Recipients object for the added document:
    Recipients recipientsAddedDoc = new Recipients
    {
        CarbonCopies = new List<CarbonCopy> { cc1 },
        Signers = new List<Signer> { signer1AddedDoc },
    };

    // create the HTML document
    Document doc1 = new Document();

    string doc1B64 = Convert.ToBase64String(Document1(signerEmail, signerName, ccEmail, ccName, item, quantity));
    doc1.DocumentBase64 = doc1B64;
    doc1.Name = "Appendix 1--Sales order"; // can be different from actual file name
    doc1.FileExtension = "html";
    doc1.DocumentId = "1";

    // create a composite template for the added document
    CompositeTemplate compTemplate2 = new CompositeTemplate
    {
        CompositeTemplateId = "2",
    };

    // Add the recipients via an inlineTemplate
    InlineTemplate inlineTemplate2 = new InlineTemplate
    {
        Sequence = "1",
        Recipients = recipientsAddedDoc,
    };
    compTemplate2.InlineTemplates = new List<InlineTemplate> { inlineTemplate2 };
    compTemplate2.Document = doc1;

    EnvelopeDefinition env = new EnvelopeDefinition
    {
        Status = "sent",
        CompositeTemplates = new List<CompositeTemplate> { compTemplate1, compTemplate2 },
    };

    return env;
}

public static byte[] Document1(
    string signerEmail,
    string signerName,
    string ccEmail,
    string ccName,
    string item,
    string quantity)
{
    // Data for this method
    // signerEmail
    // signerName
    // ccEmail
    // ccName
    // item
    // quantity
    return Encoding.UTF8.GetBytes(" <!DOCTYPE html>\n" +
            "    <html>\n" +
            "        <head>\n" +
            "          <meta charset=\"UTF-8\">\n" +
            "        </head>\n" +
            "        <body style=\"font-family:sans-serif;margin-left:2em;\">\n" +
            "        <h1 style=\"font-family: 'Trebuchet MS', Helvetica, sans-serif;\n" +
            "            color: darkblue;margin-bottom: 0;\">World Wide Corp</h1>\n" +
            "        <h2 style=\"font-family: 'Trebuchet MS', Helvetica, sans-serif;\n" +
            "          margin-top: 0px;margin-bottom: 3.5em;font-size: 1em;\n" +
            "          color: darkblue;\">Order Processing Division</h2>\n" +
            "        <h4>Ordered by " + signerName + "</h4>\n" +
            "        <p style=\"margin-top:0em; margin-bottom:0em;\">Email: " + signerEmail + "</p>\n" +
            "        <p style=\"margin-top:0em; margin-bottom:0em;\">Copy to: " + ccName + "," + ccEmail + "</p>\n" +
            "        <p style=\"margin-top:3em; margin-bottom:0em;\">Item: <b>" + item + "</b>, quantity: <b>" + quantity + "</b> at market price.</p>\n" +
            "        <p style=\"margin-top:3em;\">\n" +
            "  Candy bonbon pastry jujubes lollipop wafer biscuit biscuit. Topping brownie sesame snaps sweet roll pie. Croissant danish biscuit soufflé caramels jujubes jelly. Dragée danish caramels lemon drops dragée. Gummi bears cupcake biscuit tiramisu sugar plum pastry. Dragée gummies applicake pudding liquorice. Donut jujubes oat cake jelly-o. Dessert bear claw chocolate cake gummies lollipop sugar plum ice cream gummies cheesecake.\n" +
            "        </p>\n" +
            "        <!-- Note the anchor tag for the signature field is in white. -->\n" +
            "        <h3 style=\"margin-top:3em;\">Agreed: <span style=\"color:white;\">**signature_1**/</span></h3>\n" +
            "        </body>\n" +
            "    </html>");
}
```

**`Java`**

```java title="Java"
	public static EnvelopeDefinition makeEnvelope(
			String signerEmail,
			String signerName,
			String signerClientId,
			String ccEmail,
			String ccName,
			String templateId,
			WorkArguments args) throws IOException {
		// Create a signer and cc recipients for the signer role of the server template
		CarbonCopy cc1 = new CarbonCopy();
		cc1.setEmail(ccEmail);
		cc1.setName(ccName);
		cc1.setRoleName(EnvelopeHelpers.CC_ROLE_NAME);
		cc1.setRecipientId("2");

		// create a composite template for the Server Template
		CompositeTemplate compTemplate1 = new CompositeTemplate();
		compTemplate1.setCompositeTemplateId("1");
		ServerTemplate serverTemplates = new ServerTemplate();
		serverTemplates.setSequence("1");
		serverTemplates.setTemplateId(templateId);
		compTemplate1.setServerTemplates(Collections.singletonList(serverTemplates));

		// Add the roles via an inlineTemplate
		InlineTemplate inlineTemplate = new InlineTemplate();
		inlineTemplate.setSequence("2");
		inlineTemplate.setRecipients(EnvelopeHelpers.createRecipients(
				createSigner(
						signerEmail,
						signerName,
						signerClientId),
				cc1));
		compTemplate1.setInlineTemplates(Collections.singletonList(inlineTemplate));

		// The signer recipient for the added document with a tab definition:
		Tabs signer1Tabs = EnvelopeHelpers.createSingleSignerTab(
				"**signature_1**",
				ANCHOR_OFFSET_Y,
				ANCHOR_OFFSET_X);
		Signer signer1AddedDoc = createSigner(
				signerEmail,
				signerName,
				signerClientId);
		signer1AddedDoc.setTabs(signer1Tabs);

		// create the HTML document
		byte[] htmlDoc = EnvelopeHelpers.createHtmlFromTemplateFile(HTML_DOCUMENT_FILE_NAME, "args", args)
				.getBytes(StandardCharsets.UTF_8);

		// create a composite template for the added document and add the recipients via
		// an inlineTemplate
		CompositeTemplate compTemplate2 = new CompositeTemplate();
		compTemplate2.setCompositeTemplateId("2");
		InlineTemplate inlineTemplate2 = new InlineTemplate();
		inlineTemplate2.setSequence("1");
		inlineTemplate2.setRecipients(EnvelopeHelpers.createRecipients(signer1AddedDoc, cc1));
		compTemplate2.setInlineTemplates(Collections.singletonList(inlineTemplate2));
		compTemplate2.setDocument(EnvelopeHelpers.createDocument(htmlDoc, HTML_DOCUMENT_NAME,
				DocumentType.HTML.getDefaultFileExtention(), "1"));

		EnvelopeDefinition envelopeDefinition = new EnvelopeDefinition();
		envelopeDefinition.setStatus(EnvelopeHelpers.ENVELOPE_STATUS_SENT);
		envelopeDefinition.setCompositeTemplates(Arrays.asList(compTemplate1, compTemplate2));

		return envelopeDefinition;
	}
```

**`Node.js`**

```javascript title="Node.js"
function makeEnvelope(args) {
  // Data for this method
  // args.signerEmail
  // args.signerName
  // args.signerClientId
  // args.ccEmail
  // args.ccName
  // args.templateId

  // The envelope request object uses Composite Template to
  // include in the envelope:
  // 1. A template stored on the DocuSign service
  // 2. An additional document which is a custom HTML source document

  // Create Recipients for server template. Note that Recipients object
  // is used, not TemplateRole
  //
  // Create a signer recipient for the signer role of the server template
  let signer1 = docusign.Signer.constructFromObject({
    email: args.signerEmail,
    name: args.signerName,
    roleName: 'signer',
    recipientId: '1',
    // Adding clientUserId transforms the template recipient
    // into an embedded recipient:
    clientUserId: args.signerClientId,
  });
  // Create the cc recipient
  let cc1 = docusign.CarbonCopy.constructFromObject({
    email: args.ccEmail,
    name: args.ccName,
    roleName: 'cc',
    recipientId: '2',
  });
  // Recipients object:
  let recipientsServerTemplate = docusign.Recipients.constructFromObject({
    carbonCopies: [cc1],
    signers: [signer1],
  });

  // create a composite template for the Server Template
  let compTemplate1 = docusign.CompositeTemplate.constructFromObject({
    compositeTemplateId: '1',
    serverTemplates: [
      docusign.ServerTemplate.constructFromObject({
        sequence: '1',
        templateId: args.templateId,
      }),
    ],
    // Add the roles via an inlineTemplate
    inlineTemplates: [
      docusign.InlineTemplate.constructFromObject({
        sequence: '2',
        recipients: recipientsServerTemplate,
      }),
    ],
  });

  // The signer recipient for the added document with
  // a tab definition:
  let signHere1 = docusign.SignHere.constructFromObject({
    anchorString: '**signature_1**',
    anchorYOffset: '10',
    anchorUnits: 'pixels',
    anchorXOffset: '20',
  });
  let signer1Tabs = docusign.Tabs.constructFromObject({
    signHereTabs: [signHere1],
  });

  // Signer definition for the added document
  let signer1AddedDoc = docusign.Signer.constructFromObject({
    email: args.signerEmail,
    name: args.signerName,
    clientId: args.signerClientId,
    roleName: 'signer',
    recipientId: '1',
    tabs: signer1Tabs,
  });
  // Recipients object for the added document:
  let recipientsAddedDoc = docusign.Recipients.constructFromObject({
    carbonCopies: [cc1],
    signers: [signer1AddedDoc],
  });
  // create the HTML document
  let doc1 = new docusign.Document();
    let doc1b64 = Buffer.from(document1(args)).toString('base64');
  doc1.documentBase64 = doc1b64;
  doc1.name = 'Appendix 1--Sales order'; // can be different from actual file name
  doc1.fileExtension = 'html';
  doc1.documentId = '1';

  // create a composite template for the added document
  let compTemplate2 = docusign.CompositeTemplate.constructFromObject({
    compositeTemplateId: '2',
    // Add the recipients via an inlineTemplate
    inlineTemplates: [
      docusign.InlineTemplate.constructFromObject({
        sequence: '1',
        recipients: recipientsAddedDoc,
      }),
    ],
    document: doc1,
  });

  // create the envelope definition
  let env = docusign.EnvelopeDefinition.constructFromObject({
    status: 'sent',
    compositeTemplates: [compTemplate1, compTemplate2],
  });

  return env;
}
```

**`PHP`**

```php title="PHP"
public static function makeEnvelope(array $args, $clientService): EnvelopeDefinition
{
    # 1. Create Recipients for server template. Note that Recipients object
    #    is used, not TemplateRole
    #
    # Create a signer recipient for the signer role of the server template
    $signer1 = new Signer([
        'email' => $args['signer_email'], 'name' => $args['signer_name'],
        'role_name' => "signer", 'recipient_id' => "1",
        # Adding clientUserId transforms the template recipient
        # into an embedded recipient:
        'client_user_id' => $args['signer_client_id']
    ]);
    # Create the cc recipient
    $cc1 = new CarbonCopy([
        'email' => $args['cc_email'], 'name' => $args['cc_name'],
        'role_name' => "cc", 'recipient_id' => "2"
    ]);
    # Recipients object:
    $recipients_server_template = new Recipients([
        'carbon_copies' => [$cc1], 'signers' => [$signer1]]);

    # 2. create a composite template for the Server template + roles
    $comp_template1 = new CompositeTemplate([
        'composite_template_id' => "1",
        'server_templates' => [
            new ServerTemplate([
                'sequence' => "1", 'template_id' => $args['template_id']])
        ],
        # Add the roles via an inlineTemplate
        'inline_templates' => [
            new InlineTemplate([
                'sequence' => "2",
                'recipients' => $recipients_server_template])
        ]
    ]);

    # Next, create the second composite template that will
    # include the new document.
    #
    # 3. Create the signer recipient for the added document
    #    starting with the tab definition:
    $sign_here1 = new SignHere([
        'anchor_string' => '**signature_1**',
        'anchor_y_offset' => '10', 'anchor_units' => 'pixels',
        'anchor_x_offset' => '20']);
    $signer1_tabs = new Tabs([
        'sign_here_tabs' => [$sign_here1]]);

    # 4. Create Signer definition for the added document
    $signer1AddedDoc = new Signer([
        'email' => $args['signer_email'],
        'name' => $args['signer_name'],
                                      'role_name' => "signer",
                                      'recipient_id' => "1",
                                      'client_user_id' => $args['signer_client_id'],
                                      'tabs' => $signer1_tabs
                                  ]);

    # 5. The Recipients object for the added document.
    #    Using cc1 definition from above.
    $recipients_added_doc = new Recipients(
        [
            'carbon_copies' => [$cc1],
            'signers' => [$signer1AddedDoc]
        ]
    );

    # 6. Create the HTML document that will be added to the envelope
    $doc1_b64 = base64_encode($clientService->createDocumentForEnvelope($args));
    $doc1 = new Document(
        [
            'document_base64' => $doc1_b64,
            'name' => 'Appendix 1--Sales order', # can be different from
            # actual file name
            'file_extension' => 'html',
            'document_id' => '1'
        ]
    );

    # 6. create a composite template for the added document
    $comp_template2 = new CompositeTemplate(
        [
            'composite_template_id' => "2",
            # Add the recipients via an inlineTemplate
            'inline_templates' => [
                new InlineTemplate(
                    [
                        'sequence' => "1",
                        'recipients' => $recipients_added_doc
                    ]
                )
            ],
            'document' => $doc1
        ]
    );

    # 7. create the envelope definition with the composited templates
    return new EnvelopeDefinition(
        [
            'status' => "sent",
            'composite_templates' => [$comp_template1, $comp_template2]
        ]
    );
}
```

**`PowerShell`**

```text title="PowerShell"
@{
    compositeTemplates = @(
        @{
            compositeTemplateId = "1";
            inlineTemplates     = @(
                @{
                    recipients = @{
                        carbonCopies = @(
                            @{
                                email       = $variables.CC_EMAIL;
                                name        = $variables.CC_NAME;
                                recipientId = "2";
                                roleName    = "cc";
                            };
                        );
                        signers      = @(
                            @{
                                clientUserId = "1000";
                                email        = $variables.SIGNER_EMAIL;
                                name         = $variables.SIGNER_NAME;
                                recipientId  = "1";
                                roleName     = "signer";
                            };
                        );
                    };
                    sequence   = "2";
                };
            );
            serverTemplates     = @(
                @{
                    sequence   = "1";
                    templateId = "$templateId";
                };
            );
        };
        @{
            compositeTemplateId = "2";
            document            = @{
                documentBase64 = "$(Get-Content $doc1Base64)";
                documentId     = "1";
                fileExtension  = "html";
                name           = "Appendix 1--Sales order";
            };
            inlineTemplates     = @(
                @{
                    recipients = @{
                        carbonCopies = @(
                            @{
                                email       = $variables.CC_EMAIL;
                                name        = $variables.CC_NAME;
                                recipientId = "2";
                                roleName    = "cc";
                            };
                        );
                        signers      = @(
                            @{
                                email       = $variables.SIGNER_EMAIL;
                                name        = $variables.SIGNER_NAME;
                                recipientId = "1";
                                roleName    = "signer";
                                tabs        = @{
                                    signHereTabs = @(
                                        @{
                                            anchorString  = "**signature_1**";
                                            anchorUnits   = "pixels";
                                            anchorXOffset = "20";
                                            anchorYOffset = "10";
                                        };
                                    );
                                };
                            };
                        );
                    };
                    sequence   = "1";
                };
            );
        };
    );
    status             = "sent";
} | ConvertTo-Json -Depth 32 > $requestData
```

**`Python`**

```python title="Python"
def make_envelope(cls, args):
    """
    Creates envelope
    Uses compositing templates to add a new document to the existing template
    returns an envelope definition

    The envelope request object uses Composite Template to
    include in the envelope:
    1. A template stored on the DocuSign service
    2. An additional document which is a custom HTML source document
    """

    # Create Recipients for server template. Note that Recipients object
    # is used, not TemplateRole
    #
    # Create a signer recipient for the signer role of the server template
    signer1 = Signer(
        email=args["signer_email"],
        name=args["signer_name"],
        role_name="signer",
        recipient_id="1",
        # Adding clientUserId transforms the template recipient
        # into an embedded recipient:
        client_user_id=args["signer_client_id"]
    )
    # Create the cc recipient
    cc1 = CarbonCopy(
        email=args["cc_email"],
        name=args["cc_name"],
        role_name="cc",
        recipient_id="2"
    )
    # Recipients object:
    recipients_server_template = Recipients(
        carbon_copies=[cc1],
        signers=[signer1]
    )

    # Create a composite template for the Server template + roles
    comp_template1 = CompositeTemplate(
        composite_template_id="1",
        server_templates=[
            ServerTemplate(sequence="1", template_id=args["template_id"])
        ],
        # Add the roles via an inlineTemplate
        inline_templates=[
            InlineTemplate(sequence="2",
                           recipients=recipients_server_template)
        ]
    )

    # Next, create the second composite template that will
    # include the new document.
    #
    # Create the signer recipient for the added document
    # starting with the tab definition:
    sign_here1 = SignHere(
        anchor_string="**signature_1**",
        anchor_y_offset="10",
        anchor_units="pixels",
        anchor_x_offset="20"
    )
    signer1_tabs = Tabs(sign_here_tabs=[sign_here1])

    # Create Signer definition for the added document
    signer1_added_doc = Signer(
        email=args["signer_email"],
        name=args["signer_name"],
        role_name="signer",
        recipient_id="1",
        client_user_id=args["signer_client_id"],
        tabs=signer1_tabs
    )
    # The Recipients object for the added document.
    # using cc1 definition from above.
    recipients_added_doc = Recipients(
        carbon_copies=[cc1], signers=[signer1_added_doc])
    # Create the HTML document that will be added to the envelope
    doc1_b64 = base64.b64encode(bytes(cls.create_document1(args), "utf-8")) \
        .decode("ascii")
    doc1 = Document(
        document_base64=doc1_b64,
        name="Appendix 1--Sales order",  # can be different from
        # actual file name
        file_extension="html",
        document_id="1"
    )
    # Create a composite template for the added document
    comp_template2 = CompositeTemplate(
        composite_template_id="2",
        # Add the recipients via an inlineTemplate
        inline_templates=[
            InlineTemplate(sequence="1", recipients=recipients_added_doc)
        ],
        document=doc1
    )
    # Create the envelope definition with the composited templates
    envelope_definition = EnvelopeDefinition(
        status="sent",
        composite_templates=[comp_template1, comp_template2]
    )

    return envelope_definition

@classmethod
def create_document1(cls, args):
    return f"""
    <!DOCTYPE html>
    <html>
        <head>
          <meta charset="UTF-8">
        </head>
        <body style="font-family:sans-serif;margin-left:2em;">
        <h1 style="font-family: "Trebuchet MS", Helvetica, sans-serif;
            color: darkblue;margin-bottom: 0;">World Wide Corp</h1>
        <h2 style="font-family: "Trebuchet MS", Helvetica, sans-serif;
          margin-top: 0px;margin-bottom: 3.5em;font-size: 1em;
          color: darkblue;">Order Processing Division</h2>
        <h4>Ordered by {args["signer_name"]}</h4>
        <p style="margin-top:0em; margin-bottom:0em;">Email: {args["signer_email"]}</p>
        <p style="margin-top:0em; margin-bottom:0em;">Copy to: {args["cc_name"]}, {args["cc_email"]}</p>
        <p style="margin-top:3em; margin-bottom:0em;">Item: <b>{args["item"]}</b>, quantity: <b>{args["quantity"]}</b> at market price.</p>
        <p style="margin-top:3em;">
  Candy bonbon pastry jujubes lollipop wafer biscuit biscuit. Topping brownie sesame snaps sweet roll pie. Croissant danish biscuit soufflé caramels jujubes jelly. Dragée danish caramels lemon drops dragée. Gummi bears cupcake biscuit tiramisu sugar plum pastry. Dragée gummies applicake pudding liquorice. Donut jujubes oat cake jelly-o. Dessert bear claw chocolate cake gummies lollipop sugar plum ice cream gummies cheesecake.
        </p>
        <!-- Note the anchor tag for the signature field is in white. -->
        <h3 style="margin-top:3em;">Agreed: <span style="color:white;">**signature_1**/</span></h3>
        </body>
    </html>
  """
```

**`Ruby`**

```ruby title="Ruby"
def make_envelope(args)
  # 1. Create recipients for server template. Note that the Recipients object
  #    is used, not TemplateRole
  #
  # Create a signer recipient for the signer role of the server template
  signer1 = DocuSign_eSign::Signer.new(
    email: args[:signer_email], name: args[:signer_name],
    roleName: 'signer', recipientId: '1',
    # Adding clientUserId transforms the template recipient into an embedded recipient
    clientUserId: args[:signer_client_id]
  )
  cc1 = DocuSign_eSign::CarbonCopy.new(
    email: args[:cc_email], name: args[:cc_name],
    roleName: 'cc', recipientId: '2'
  )
  # Recipients object
  recipients_server_template = DocuSign_eSign::Recipients.new(
    'carbonCopies' => [cc1], 'signers' => [signer1]
  )

  # 2. Create a composite template for the Server template + roles
  comp_template1 = DocuSign_eSign::CompositeTemplate.new(
    compositeTemplate_id: '1',
    serverTemplates: [DocuSign_eSign::ServerTemplate.new(
      sequence: '1', templateId: args[:template_id]
    )],
    # Add the roles via an inlineTemplate
    inlineTemplates: [
      DocuSign_eSign::InlineTemplate.new(
        'sequence' => '2',
        'recipients' => recipients_server_template
      )
    ]
  )

  # Next, create the second composite template that will include the new document
  #
  # 3. Create the signer recipient for the added document
  #    starting with the tab definition:
  sign_here1 = DocuSign_eSign::SignHere.new(
    anchorString: '**signature_1**',
    anchorYOffset: '10', anchorUnits: 'pixels',
    anchorXOffset: '20'
  )
  signer1_tabs = DocuSign_eSign::Tabs.new('signHereTabs' => [sign_here1])

  # 4. Create Signer definition for the added document
  signer1AddedDoc = DocuSign_eSign::Signer.new(
    email: args[:signer_email],
    name: args[:signer_name],
    roleName: 'signer', recipientId: '1',
    clientUserId: args[:signer_client_id],
    tabs: signer1_tabs
  )

  # 5. The Recipients object for the added document using cc1 definition from above
  recipients_added_doc = DocuSign_eSign::Recipients.new(
    carbonCopies: [cc1], signers: [signer1AddedDoc]
  )

  # 6. Create the HTML document that will be added to the envelope
  doc1_b64 = Base64.encode64(create_document1(args))
  doc1 = DocuSign_eSign::Document.new(
    documentBase64: doc1_b64,
    name: 'Appendix 1--Sales order', # Can be different from actual file name
    fileExtension: 'html', documentId: '1'
  )

  # 7. Create a composite template for the added document
  comp_template2 = DocuSign_eSign::CompositeTemplate.new(
    compositeTemplateId: '2',
    # Add the recipients via an inlineTemplate
    inlineTemplates: [
      DocuSign_eSign::InlineTemplate.new(
        sequence: '1', recipients: recipients_added_doc
      )
    ],
    document: doc1
  )
  # 8. Create the envelope definition with the composited templates
  DocuSign_eSign::EnvelopeDefinition.new(
    status: 'sent',
    compositeTemplates: [comp_template1, comp_template2]
  )
end

def create_document1(args)
  <<~HEREDOC
        <!DOCTYPE html>
        <html>
            <head>
              <meta charset="UTF-8">
            </head>
            <body style="font-family:sans-serif;margin-left:2em;">
            <h1 style="font-family: 'Trebuchet MS', Helvetica, sans-serif;
    color: darkblue;margin-bottom: 0;">World Wide Corp</h1>
            <h2 style="font-family: 'Trebuchet MS', Helvetica, sans-serif;
    margin-top: 0px;margin-bottom: 3.5em;font-size: 1em;
    color: darkblue;">Order Processing Division</h2>
            <h4>Ordered by #{args[:signer_name]}</h4>
            <p style="margin-top:0em; margin-bottom:0em;">Email: #{args[:signer_email]}</p>
            <p style="margin-top:0em; margin-bottom:0em;">Copy to: #{args[:cc_name]}, #{args[:cc_email]}</p>
            <p style="margin-top:3em; margin-bottom:0em;">Item: <b>#{args[:item]}</b>, quantity: <b>#{args[:quantity]}</b> at market price.</p>
            <p style="margin-top:3em;">
      Candy bonbon pastry jujubes lollipop wafer biscuit biscuit. Topping brownie sesame snaps sweet roll pie. Croissant danish biscuit soufflé caramels jujubes jelly. Dragée danish caramels lemon drops dragée. Gummi bears cupcake biscuit tiramisu sugar plum pastry. Dragée gummies applicake pudding liquorice. Donut jujubes oat cake jelly-o. Dessert bear claw chocolate cake gummies lollipop sugar plum ice cream gummies cheesecake.
            </p>
            <!-- Note the anchor tag for the signature field is in white. -->
            <h3 style="margin-top:3em;">Agreed: <span style="color:white;">**signature_1**/</span></h3>
            </body>
        </html>
  HEREDOC
end
```

## Step 3. Call Docusign to create the envelope

Next, create the envelope from the definition that you created in the previous step, then create the recipient view for embedded signing.

1. Instantiate the Docusign API client.
2. Set the following default request header to add your access token.

`"Authorization" : "Bearer {ACCESS_TOKEN}"`
3\. Initialize the Envelopes API.
4\. Create an envelope by passing in the generated envelope definition and your API account ID.

**`Bash`**

```bash title="Bash"
curl --header "Authorization: Bearer ${ACCESS_TOKEN}" \
     --header "Content-Type: application/json" \
     --data-binary @${request_data} \
     --request POST ${base_path}/v2.1/accounts/${account_id}/envelopes \
     --output $response
```

**`C#`**

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

// Step 1. Make the envelope request body
EnvelopeDefinition envelope = MakeEnvelope(signerEmail, signerName, ccEmail, ccName, item, quantity, signerClientId, templateId);

// Step 2. call Envelopes::create API method
// Exceptions will be caught by the calling function
var results = envelopesApi.CreateEnvelopeWithHttpInfo(accountId, envelope);

results.Headers.TryGetValue("X-RateLimit-Remaining", out string remaining);
results.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);
}

string envelopeId = results.Data.EnvelopeId;
Console.WriteLine("Envelope was created. EnvelopeId " + envelopeId);
```

**`Java`**

```java title="Java"
		var envelopeSummary = envelopesApi.createEnvelopeWithHttpInfo(accountId, envelope,
				envelopesApi.new CreateEnvelopeOptions());
		Map<String, java.util.List<String>> headers = envelopeSummary.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);
		}
```

**`Node.js`**

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

// Step 1. Make the envelope request body
let envelope = makeEnvelope(args.envelopeArgs);

// Step 2. call Envelopes::create API method
// Exceptions will be caught by the calling function
let results = await envelopesApi.createEnvelope(args.accountId, {
  envelopeDefinition: envelope,
}, (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();
$envelopeResponse = $envelope_api->createEnvelopeWithHttpInfo($args['account_id'], $envelope_definition);

$remaining = $envelopeResponse[2]['X-RateLimit-Remaining'] ?? null;
$reset = $envelopeResponse[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));
}

$envelope_id = $envelopeResponse[0]->getEnvelopeId();
```

**`PowerShell`**

```text title="PowerShell"
Invoke-RestMethod `
    -Uri "${apiUri}/v2.1/accounts/${accountId}/envelopes" `
    -Method 'POST' `
    -Headers @{
    'Authorization' = "Bearer $accessToken";
    'Content-Type'  = "application/json";
} `
    -InFile (Resolve-Path $requestData).Path `
    -OutFile $response
```

**`Python`**

```python title="Python"
envelope_args = args["envelope_args"]
# Create the envelope request object
envelope_definition = cls.make_envelope(envelope_args)

# Call Envelopes::create API method
# Exceptions will be caught by the calling function
api_client = create_api_client(base_path=args["base_path"], access_token=args["access_token"])

envelope_api = EnvelopesApi(api_client)
(results, 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}")

envelope_id = results.envelope_id
```

**`Ruby`**

```ruby title="Ruby"
def worker
  envelope_args = args[:envelope_args]
  # 1. Create the envelope request object
  envelope_definition = make_envelope(envelope_args)
  # 2. call Envelopes::create API method
  # Exceptions will be caught by the calling function
  envelope_api = create_envelope_api(args)

  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

  envelope_id = results.envelope_id
```

## Step 4. Create the recipient view definition

The recipient view is the screen that Docusign generates and displays in your app to enable your signers to sign documents. The recipient view request returns a link that enables your recipients to sign documents from your app. To create the definition, you must add the signer's information and the redirect URI.

1. Set the redirect URI to which the user will be forwarded after signing is complete. This URI must exactly match one that is preregistered for the integration key in your Docusign account.

   **Note**: You can include a `state` parameter in the URI string to record your application's state and provide recovery information, potentially enabling it to resume interrupted operations using only callback data.
2. Add the recipient information to the view, including the signer's email, name, and client user ID.

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

**`Bash`**

```bash title="Bash"
curl --header "Authorization: Bearer ${ACCESS_TOKEN}" \
     --header "Content-Type: application/json" \
     --data-binary '
{
    "returnUrl": "http://httpbin.org/get",
    "authenticationMethod": "none",
    "email": "'"${SIGNER_EMAIL}"'",
    "userName": "'"${SIGNER_NAME}"'",
    "clientUserId": 1000,
}' \
     --request POST ${base_path}/v2.1/accounts/${account_id}/envelopes/${envelope_id}/views/recipient \
     --output ${response}
```

**`C#`**

```csharp title="C#"
RecipientViewRequest viewRequest = MakeRecipientViewRequest(signerEmail, signerName, returnUrl, signerClientId);
var results1 = envelopesApi.CreateRecipientViewWithHttpInfo(accountId, envelopeId, viewRequest);

results1.Headers.TryGetValue("X-RateLimit-Remaining", out remaining);
results1.Headers.TryGetValue("X-RateLimit-Reset", out 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);
}
```

**`Java`**

```java title="Java"
		RecipientViewRequest viewRequest = AddDocToTemplateService.makeRecipientViewRequest(
				dsReturnUrl,
				signerEmail,
				signerName,
				dsPingUrl);
		var createRecipientView = envelopesApi.createRecipientViewWithHttpInfo(accountId,
				envelopeSummary.getData().getEnvelopeId(), viewRequest);
		headers = envelopeSummary.getHeaders();
		remaining = headers.get("X-RateLimit-Remaining");
		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 createRecipientView.getData();
	}

	public static RecipientViewRequest makeRecipientViewRequest(
			String dsReturnUrl,
			String signerEmail,
			String signerName,
			String dsPingUrl) {
		RecipientViewRequest viewRequest = new RecipientViewRequest();
		// Set the url where you want the recipient to go once they are done signing
		// should typically be a callback route somewhere in your app.
		viewRequest.setReturnUrl(dsReturnUrl);
		return SetTabValuesService.setEmailAndSignerNameForRecipientViewRequest(
				viewRequest,
				signerEmail,
				signerName,
				dsPingUrl);
	}
```

**`Node.js`**

```javascript title="Node.js"
let viewRequest = makeRecipientViewRequest(args.envelopeArgs);
// Call the CreateRecipientView API
// Exceptions will be caught by the calling function
results = await envelopesApi.createRecipientView(args.accountId, envelopeId, {
  recipientViewRequest: viewRequest,
}, (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()}`);
    }
});
function makeRecipientViewRequest(args) {
// Data for this method
// args.dsReturnUrl
// args.signerEmail
// args.signerName
// args.signerClientId
// args.dsPingUrl

let viewRequest = new docusign.RecipientViewRequest();

// Set the url where you want the recipient to go once they are done signing
// should typically be a callback route somewhere in your app.
viewRequest.returnUrl = args.dsReturnUrl;

// How has your app authenticated the user? In addition to your app's
// authentication, you can include authenticate steps from DocuSign.
// Eg, SMS authentication
viewRequest.authenticationMethod = 'none';

// Recipient information must match embedded recipient info
// we used to create the envelope.
viewRequest.email = args.signerEmail;
viewRequest.userName = args.signerName;
viewRequest.clientUserId = args.signerClientId;

// DocuSign recommends that you redirect to DocuSign for the
// embedded signing. There are multiple ways to save state.
// To maintain your application's session, use the pingUrl
// parameter. It causes the DocuSign signing web page
// (not the DocuSign server) to send pings via AJAX to your
// app,
viewRequest.pingFrequency = 600; // seconds
// NOTE: The pings will only be sent if the pingUrl is an https address
viewRequest.pingUrl = args.dsPingUrl; // optional setting

return viewRequest;
}
```

**`PHP`**

```php title="PHP"
# Create the Recipient View request object
$authentication_method = 'None'; # How is this application authenticating
# the signer? See the `authentication_method' definition
# https://developers.docusign.com/esign-rest-api/reference/Envelopes/EnvelopeViews/createRecipient
$recipient_view_request = $clientService->getRecipientViewRequest(
    $authentication_method,
    $args["envelope_args"]
);

# Obtain the recipient_view_url for the embedded signing
# Exceptions will be caught by the calling function
$recipientView = $clientService->getRecipientView($args['account_id'], $envelope_id, $recipient_view_request);

return ['envelope_id' => $envelope_id, 'redirect_url' => $recipientView['url']];
```

**`PowerShell`**

```text title="PowerShell"
Write-Output "Requesting the url for the embedded signing..."

@{
    returnUrl            = "http://httpbin.org/get";
    authenticationMethod = "none";
    email                = $variables.SIGNER_EMAIL;
    userName             = $variables.SIGNER_NAME;
    clientUserId         = 1000;
} | ConvertTo-Json -Depth 32 > $requestData

Invoke-RestMethod `
    -Uri "${apiUri}/v2.1/accounts/${accountId}/envelopes/${envelopeId}/views/recipient" `
    -Method 'POST' `
    -Headers @{
    'Authorization' = "Bearer $accessToken";
    'Content-Type'  = "application/json";
} `
    -InFile (Resolve-Path $requestData).Path`
    -OutFile $response

Write-Output "Response:"
Get-Content $response

$signingUrl = $(Get-Content $response | ConvertFrom-Json).url
```

**`Python`**

```python title="Python"
authentication_method = "None"  # How is this application authenticating
# the signer? See the "authenticationMethod" definition
# https://goo.gl/qUhGTm
recipient_view_request = RecipientViewRequest(
    authentication_method=authentication_method,
    client_user_id=envelope_args["signer_client_id"],
    recipient_id="1",
    return_url=envelope_args["ds_return_url"],
    user_name=envelope_args["signer_name"],
    email=envelope_args["signer_email"]
)
# Obtain the recipient_view_url for the embedded signing
# Exceptions will be caught by the calling function
(results, status, headers) = envelope_api.create_recipient_view_with_http_info(
    account_id=args["account_id"],
    envelope_id=envelope_id,
    recipient_view_request=recipient_view_request
)

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}")

return {"envelope_id": envelope_id, "redirect_url": results.url}
```

**`Ruby`**

```ruby title="Ruby"
authentication_method = 'None' # How is this application authenticating
# the signer? See the `authenticationMethod' definition
# https://developers.docusign.com/docs/esign-rest-api/reference/envelopes/envelopeviews/createrecipient/
recipient_view_request = DocuSign_eSign::RecipientViewRequest.new(
  authenticationMethod: authentication_method,
  returnUrl: envelope_args[:ds_return_url],
  userName: envelope_args[:signer_name],
  email: envelope_args[:signer_email],
  clientUserId: envelope_args[:signer_client_id]
)
# 4. Obtain the recipient_view_url for the embedded signing
# Exceptions will be caught by the calling function
results, _status, headers = envelope_api.create_recipient_view_with_http_info(args[:account_id],
                                                                              envelope_id, recipient_view_request)

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

{ envelope_id: envelope_id, redirect_url: results.url }
  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"
{
  "url": "https://demo.docusign.net/Signing/MTRedeem/v1/09f2e35e-xxxx-xxxx-xxxx-1fbc6fcf77ed?slt=eyJ0eX...i3x-4g"
}
```

## 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).
* Find out more about [templates](/docs/esign-rest-api/esign101/concepts/templates) or [composite templates](/docs/esign-rest-api/esign101/concepts/templates/composite).
* 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.