> 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 through your app

> Demonstrates how to create an envelope and request a signature using embedded signing in your app or website.

This topic demonstrates how to collect signatures directly within your app, without emailing the signer or directing them to an external URL. This process is called *embedded signing*. This topic also demonstrates how to use [AutoPlace](https://support.docusign.com/s/document-item?language=en_US\&rsc_301\&bundleId=gbo1643332197980\&topicId=ytr1578456405118.html&_LANG=enus) to automatically position tabs in a document with a specified string.

> **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. |
| \{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.                                                                                                        |
| Document to be signed | You must provide at least one document to be signed. Document used in this how-to:- [PDF file](https://github.com/docusign/code-examples-java/blob/master/src/main/resources/World_Wide_Corp_lorem.pdf)                                                                                                                |
| Return URL            | A URL to which the user will be forwarded after signing is complete.                                                                                                                                                                                                                                                   |
| \{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.                                                                                                                                                                                                                                                                        |

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

The first step in requesting a signature within your app is to define a method (called `makeEnvelope` in our example) that creates the envelope definition using the following steps:

* Add a document to the definition by saving it to a variable as a binary-encoded base64 string. If you intend to attach multiple documents, specify the document order using an array. The order of the array sets the order of the documents.
* Set the signer's data, including their name, email address, and a client user ID (any alphanumeric value is suitable). Including a client user ID automatically specifies the signer as embedded (using your app). If there are multiple signers, you must create a signer recipient for each one.

  **Note:** If the client user ID is set and either the `SignerMustHaveAccount` or `SignerMustLoginToSign` property of the account settings is set to `true`, the system throws an error.
* Create and assign signable fields (also known as tabs) for a specific signer within the document using [AutoPlace](/docs/esign-rest-api/esign101/concepts/tabs/auto-place). This how-to uses anchor tabs to generate tabs automatically in your document by searching for each occurrence of a specific string of characters in the document and adding tabs at those locations. This example uses the string "`/sn1/`" for auto-placing the signature (`signHere`) tab.

  To configure the anchor tabs, specify the number of units from the anchor text to offset the tab, as well as the string to search for and replace with a `signHereTab` within your document. You can create multiple `signHere` tabs for different locations and offsets, if needed.

  After creating the tabs, assign them to the signer created in the previous step.
* Set the envelope's `status` property. To save the envelope as a draft, set `status` to `created`. To configure the envelope to be sent immediately after it is instantiated, set `status` to `sent` instead.

**`Bash`**

```bash title="Bash"
printf \
'{
    "emailSubject": "Please sign this document set",
    "documents": [
        {
            "documentBase64": "' > $request_data
            cat $doc1_base64 >> $request_data
            printf '",
            "name": "Lorem Ipsum",
            "fileExtension": "pdf",
            "documentId": "1"
        }
    ],
    "recipients": {
        "signers": [
            {
                "email": "'"${SIGNER_EMAIL}"'",
                "name": "'"${SIGNER_NAME}"'",
                "recipientId": "1",
                "routingOrder": "1",
                "clientUserId": "1000",
                "tabs": {
                    "signHereTabs": [
                        {
                            "anchorString": "/sn1/",
                            "anchorUnits": "pixels",
                            "anchorXOffset": "20",
                            "anchorYOffset": "10"
                        }
                    ]
                }
            }
        ]
    },
    "status": "sent"
}' >> $request_data
```

**`C#`**

```csharp title="C#"
public static EnvelopeDefinition MakeEnvelope(string signerEmail, string signerName, string signerClientId, string docPdf)
{
    // Data for this method
    // signerEmail
    // signerName
    // signerClientId -- class global
    // Config.docPdf
    byte[] buffer = System.IO.File.ReadAllBytes(docPdf);

    EnvelopeDefinition envelopeDefinition = new EnvelopeDefinition();
    envelopeDefinition.EmailSubject = "Please sign this document";
    Document doc1 = new Document();

    string doc1B64 = Convert.ToBase64String(buffer);

    doc1.DocumentBase64 = doc1B64;
    doc1.Name = "Lorem Ipsum"; // can be different from actual file name
    doc1.FileExtension = "pdf";
    doc1.DocumentId = "3";

    // The order in the docs array determines the order in the envelope
    envelopeDefinition.Documents = new List<Document> { doc1 };

    // Create a signer recipient to sign the document, identified by name and email
    // We set the clientUserId to enable embedded signing for the recipient
    // We're setting the parameters via the object creation
    Signer signer1 = new Signer
    {
        Email = signerEmail,
        Name = signerName,
        ClientUserId = signerClientId,
        RecipientId = "1",
    };

    // Create signHere fields (also known as tabs) on the documents,
    // We're using anchor (autoPlace) positioning
    //
    // The DocuSign platform searches throughout your envelope's
    // documents for matching anchor strings.
    SignHere signHere1 = new SignHere
    {
        AnchorString = "/sn1/",
        AnchorUnits = "pixels",
        AnchorXOffset = "10",
        AnchorYOffset = "20",
    };

    // Tabs are set per recipient / signer
    Tabs signer1Tabs = new Tabs
    {
        SignHereTabs = new List<SignHere> { signHere1 },
    };
    signer1.Tabs = signer1Tabs;

    // Add the recipient to the envelope object
    Recipients recipients = new Recipients
    {
        Signers = new List<Signer> { signer1 },
    };
    envelopeDefinition.Recipients = recipients;

    // Request that the envelope be sent by setting |status| to "sent".
    // To request that the envelope be created as a draft, set to "created"
    envelopeDefinition.Status = "sent";

    return envelopeDefinition;
}
```

**`Java`**

```java title="Java"
public static EnvelopeDefinition makeEnvelope(
        String signerEmail,
        String signerName,
        String signerClientId,
        Integer anchorOffsetY,
        Integer anchorOffsetX,
        String documentFileName,
        String documentName) throws IOException {
    // Create a signer recipient to sign the document, identified by name and email
    // We set the clientUserId to enable embedded signing for the recipient
    Signer signer = new Signer();
    signer.setEmail(signerEmail);
    signer.setName(signerName);
    signer.clientUserId(signerClientId);
    signer.recipientId("1");
    signer.setTabs(EnvelopeHelpers.createSingleSignerTab("/sn1/", anchorOffsetY, anchorOffsetX));

    // Add the recipient to the envelope object
    Recipients recipients = new Recipients();
    recipients.setSigners(Collections.singletonList(signer));

    EnvelopeDefinition envelopeDefinition = new EnvelopeDefinition();
    envelopeDefinition.setEmailSubject("Please sign this document");
    envelopeDefinition.setRecipients(recipients);
    Document doc = EnvelopeHelpers.createDocumentFromFile(documentFileName, documentName, "3");
    envelopeDefinition.setDocuments(Collections.singletonList(doc));
    // Request that the envelope be sent by setting |status| to "sent".
    // To request that the envelope be created as a draft, set to "created"
    envelopeDefinition.setStatus(EnvelopeHelpers.ENVELOPE_STATUS_SENT);

    return envelopeDefinition;
}
```

**`Node.js`**

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

  // document 1 (pdf) has tag /sn1/
  //
  // The envelope has one recipients.
  // recipient 1 - signer

  let docPdfBytes;
  // read file from a local directory
  // The read could raise an exception if the file is not available!
  docPdfBytes = fs.readFileSync(args.docFile);

  // create the envelope definition
  let env = new docusign.EnvelopeDefinition();
  env.emailSubject = 'Please sign this document';

  // add the documents
  let doc1 = new docusign.Document();
  let doc1b64 = Buffer.from(docPdfBytes).toString('base64');
  doc1.documentBase64 = doc1b64;
  doc1.name = 'Lorem Ipsum'; // can be different from actual file name
  doc1.fileExtension = 'pdf';
  doc1.documentId = '3';

  // The order in the docs array determines the order in the envelope
  env.documents = [doc1];

  // Create a signer recipient to sign the document, identified by name and email
  // We set the clientUserId to enable embedded signing for the recipient
  // We're setting the parameters via the object creation
  let signer1 = docusign.Signer.constructFromObject({
    email: args.signerEmail,
    name: args.signerName,
    clientUserId: args.signerClientId,
    recipientId: 1,
  });

  // Create signHere fields (also known as tabs) on the documents,
  // We're using anchor (autoPlace) positioning
  //
  // The DocuSign platform seaches throughout your envelope's
  // documents for matching anchor strings.
  let signHere1 = docusign.SignHere.constructFromObject({
    anchorString: '/sn1/',
    anchorYOffset: '10',
    anchorUnits: 'pixels',
    anchorXOffset: '20',
  });
  // Tabs are set per recipient / signer
  let signer1Tabs = docusign.Tabs.constructFromObject({
    signHereTabs: [signHere1],
  });
  signer1.tabs = signer1Tabs;

  // Add the recipient to the envelope object
  let recipients = docusign.Recipients.constructFromObject({
    signers: [signer1],
  });
  env.recipients = recipients;

  // Request that the envelope be sent by setting |status| to "sent".
  // To request that the envelope be created as a draft, set to "created"
  env.status = 'sent';

  return env;
}
```

**`PHP`**

```php title="PHP"
public static function makeEnvelope(array $args, string $demoPath, string $pdfFile): EnvelopeDefinition
{
    # document 1 (pdf) has tag /sn1/
    #
    # The envelope has one recipient.
    # recipient 1 - signer
    #
    # Read the file
    $content_bytes = file_get_contents($demoPath . $pdfFile);
    $base64_file_content = base64_encode($content_bytes);

    # Create the document model
    $document = new Document(
        [ # create the DocuSign document object
            'document_base64' => $base64_file_content,
            'name' => 'Example document', # can be different from actual file name
            'file_extension' => 'pdf', # many different document types are accepted
            'document_id' => 1 # a label used to reference the doc
        ]
    );

    # Create the signer recipient model
    $signer = new Signer(
        [ # The signer
            'email' => $args['signer_email'],
            'name' => $args['signer_name'],
            'recipient_id' => "1",
            'routing_order' => "1",
            # Setting the client_user_id marks the signer as embedded
            'client_user_id' => $args['signer_client_id']
        ]
    );

    # Create a sign_here tab (field on the document)
    $sign_here = new SignHere(
        [ # DocuSign SignHere field/tab
            'anchor_string' => '/sn1/',
            'anchor_units' => 'pixels',
            'anchor_y_offset' => '10',
            'anchor_x_offset' => '20'
        ]
    );

    # Add the tabs model (including the sign_here tab) to the signer
    # The Tabs object wants arrays of the different field/tab types
    $signer->settabs(new Tabs(['sign_here_tabs' => [$sign_here]]));

    // Next, create the top level envelope definition and populate it.
    $envelope_definition = new EnvelopeDefinition(
        [
            'email_subject' => "Please sign this document sent from the PHP SDK",
            'documents' => [$document],
            # The Recipients object wants arrays for each recipient type
            'recipients' => new Recipients(['signers' => [$signer]]),
            'status' => "sent" # requests that the envelope be created and sent.
        ]
    );

    return $envelope_definition;
}
```

**`PowerShell`**

```text title="PowerShell"
@{
    emailSubject = "Please sign this document set";
    documents    = @(
        @{
            documentBase64 = "$(Get-Content $doc1Base64)";
            name           = "Lorem Ipsum";
            fileExtension  = "pdf";
            documentId     = "1";
        };
    );
    recipients   = @{
        signers      = @(
            @{
                email        = $variables.SIGNER_EMAIL;
                name         = $variables.SIGNER_NAME;
                recipientId  = "1";
                routingOrder = "1";
                clientUserId = "1000";
                tabs         = @{
                    signHereTabs = @(
                        @{
                            anchorString  = "/sn1/";
                            anchorUnits   = "pixels";
                            anchorXOffset = "20";
                            anchorYOffset = "10";
                        };
                    );
                };
            };
        );
    };
    status       = "sent";
} | ConvertTo-Json -Depth 32 > $requestData
```

**`Python`**

```python title="Python"
def make_envelope(cls, args):
    """
    Creates envelope
    args -- parameters for the envelope:
    signer_email, signer_name, signer_client_id
    returns an envelope definition
    """

    # document 1 (pdf) has tag /sn1/
    #
    # The envelope has one recipient.
    # recipient 1 - signer
    with open(path.join(demo_docs_path, DS_CONFIG["doc_pdf"]), "rb") as file:
        content_bytes = file.read()
    base64_file_content = base64.b64encode(content_bytes).decode("ascii")

    # Create the document model
    document = Document(  # create the DocuSign document object
        document_base64=base64_file_content,
        name="Example document",  # can be different from actual file name
        file_extension="pdf",  # many different document types are accepted
        document_id=1  # a label used to reference the doc
    )

    # Create the signer recipient model
    signer = Signer(
        # The signer
        email=args["signer_email"],
        name=args["signer_name"],
        recipient_id="1",
        routing_order="1",
        # Setting the client_user_id marks the signer as embedded
        client_user_id=args["signer_client_id"]
    )

    # Create a sign_here tab (field on the document)
    sign_here = SignHere(
        # DocuSign SignHere field/tab
        anchor_string="/sn1/",
        anchor_units="pixels",
        anchor_y_offset="10",
        anchor_x_offset="20"
    )

    # Add the tabs model (including the sign_here tab) to the signer
    # The Tabs object wants arrays of the different field/tab types
    signer.tabs = Tabs(sign_here_tabs=[sign_here])

    # Next, create the top level envelope definition and populate it.
    envelope_definition = EnvelopeDefinition(
        email_subject="Please sign this document sent from the Python SDK",
        documents=[document],
        # The Recipients object wants arrays for each recipient type
        recipients=Recipients(signers=[signer]),
        status="sent"  # requests that the envelope be created and sent.
    )

    return envelope_definition
```

**`Ruby`**

```ruby title="Ruby"
def make_envelope(signer_client_id, pdf_filename, signer_email, signer_name)
  envelope_definition = DocuSign_eSign::EnvelopeDefinition.new
  envelope_definition.email_subject = 'Please sign this document sent from Ruby SDK'

  doc1 = DocuSign_eSign::Document.new
  doc1.document_base64 = Base64.encode64(File.binread(pdf_filename))
  doc1.name = 'Lorem Ipsum'
  doc1.file_extension = 'pdf'
  doc1.document_id = '1'

  # The order in the docs array determines the order in the envelope
  envelope_definition.documents = [doc1]
  # Create a signer recipient to sign the document, identified by name and email
  # We're setting the parameters via the object creation
  signer1 = DocuSign_eSign::Signer.new({
                                         email: signer_email, name: signer_name,
                                         clientUserId: signer_client_id, recipientId: 1
                                       })
  # The Docusign platform searches throughout your envelope's documents for matching
  # anchor strings. So the sign_here_2 tab will be used in both document 2 and 3
  # since they use the same anchor string for their "signer 1" tabs.
  sign_here = DocuSign_eSign::SignHere.new
  sign_here.anchor_string = '/sn1/'
  sign_here.anchor_units = 'pixels'
  sign_here.anchor_x_offset = '20'
  sign_here.anchor_y_offset = '10'
  # Tabs are set per recipient/signer
  tabs = DocuSign_eSign::Tabs.new
  tabs.sign_here_tabs = [sign_here]
  signer1.tabs = tabs
  # Add the recipients to the envelope object
  recipients = DocuSign_eSign::Recipients.new
  recipients.signers = [signer1]

  envelope_definition.recipients = recipients
  # Request that the envelope be sent by setting status to "sent".
  # To request that the envelope be created as a draft, set status to "created"
  envelope_definition.status = 'sent'
  envelope_definition
end
```

## Step 3. Call Docusign to create the envelope

With the envelope definition and the attributes defined for the signer, document, and custom fields, you can now use the [Envelopes:create](/docs/esign-rest-api/reference/envelopes/envelopes/create) endpoint to create an envelope for the transaction.

* First, instantiate a new instance of the API client (if you're using a Docusign SDK).
* Set the following default request header to add your access token to all API calls.
  `"Authorization: Bearer ${ACCESS_TOKEN}"`
* Initialize the Envelopes API.
* Using your Docusign integration key and the prepared envelope definition, generate and retrieve an envelope ID using the [Envelopes:create](/docs/esign-rest-api/reference/envelopes/envelopes/create) endpoint.

**`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#"
EnvelopeDefinition envelope = MakeEnvelope(signerEmail, signerName, signerClientId, docPdf);

var docuSignClient = new DocuSignClient(basePath);
docuSignClient.Configuration.DefaultHeader.Add("Authorization", "Bearer " + accessToken);

EnvelopesApi envelopesApi = new EnvelopesApi(docuSignClient);
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;
```

**`Java`**

```java title="Java"
EnvelopeDefinition envelope = EmbeddedSigningService.makeEnvelope(
        signerEmail,
        signerName,
        SIGNER_CLIENT_ID,
        ANCHOR_OFFSET_Y,
        ANCHOR_OFFSET_X,
        DOCUMENT_FILE_NAME,
        DOCUMENT_NAME);

// Call DocuSign to create the envelope
ApiClient apiClient = createApiClient(session.getBasePath(), user.getAccessToken());

String envelopeId = EmbeddedSigningService.createEnvelope(apiClient, session.getAccountId(), envelope);
```

**`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);
let results = null;

// 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
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_definition = EmbeddedSigningService::makeEnvelope($args["envelope_args"], $demoPath, $pdfFile);
$envelope_api = $clientService->getEnvelopeApi();

# Call Envelopes::create API method
# Exceptions will be caught by the calling function
try {
    $envelopeSummary = $envelope_api->createEnvelopeWithHttpInfo($args['account_id'], $envelope_definition);
    $remaining = $envelopeSummary[2]['X-RateLimit-Remaining'] ?? null;
    $reset = $envelopeSummary[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));
    }
} catch (ApiException $e) {
    $clientService->showErrorTemplate($e);
    exit;
}
$envelope_id = $envelopeSummary[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"]
# 1. Create the envelope request object
envelope_definition = cls.make_envelope(envelope_args)

# 2. 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)
(data, 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 = data.envelope_id
```

**`Ruby`**

```ruby title="Ruby"
envelope = make_envelope(args[:signer_client_id], pdf_filename, signer_email, signer_name)

# Call Docusign to create the envelope
envelope_api = create_envelope_api(args)

results, _status, headers = envelope_api.create_envelope_with_http_info args[:account_id], envelope

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. To create the definition, you must add the signer's information and the return URL.

* Set the return URL to which the user will be forwarded after signing is complete.
* Add the recipient information to the view, including the signer's `email`, `name`, and `clientUserID` that were set for the recipient who will sign the envelope.

**`Bash`**

```bash title="Bash"
printf \
'{
    "returnUrl": "http://httpbin.org/get",
    "authenticationMethod": "none",
    "email": "'"${SIGNER_EMAIL}"'",
    "userName": "'"${SIGNER_NAME}"'",
    "clientUserId": 1000,
}' >> $request_data
```

**`C#`**

```csharp title="C#"
public static RecipientViewRequest MakeRecipientViewRequest(string signerEmail, string signerName, string returnUrl, string signerClientId, string pingUrl = null)
{
    // Data for this method
    // signerEmail
    // signerName
    // dsPingUrl -- class global
    // signerClientId -- class global
    // dsReturnUrl -- class global
    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.
    // The query parameter is included as an example of how
    // to save/recover state information during the redirect to
    // the DocuSign signing ceremony. It's usually better to use
    // the session mechanism of your web framework. Query parameters
    // can be changed/spoofed very easily.
    viewRequest.ReturnUrl = returnUrl + "?state=123";

    // 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 = signerEmail;
    viewRequest.UserName = signerName;
    viewRequest.ClientUserId = signerClientId;

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

    return viewRequest;
}
```

**`Java`**

```java title="Java"
public static RecipientViewRequest makeRecipientViewRequest(
        String signerEmail,
        String signerName,
        String clientUserId,
        String dsReturnURL,
        String pingURL) {
    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.
    // The query parameter is included as an example of how
    // to save/recover state information during the redirect to
    // the DocuSign signing. It's usually better to use
    // the session mechanism of your web framework. Query parameters
    // can be changed/spoofed very easily.
    String stateValue = "?state=123";
    viewRequest.setReturnUrl(dsReturnURL + stateValue);

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

    // Recipient information must match embedded recipient info
    // we used to create the envelope.
    viewRequest.setEmail(signerEmail);
    viewRequest.setUserName(signerName);
    viewRequest.setClientUserId(clientUserId);

    // 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.
    // NOTE: The pings will only be sent if the pingUrl is an https address
    String pingFrequency = "600";
    viewRequest.setPingFrequency(pingFrequency); // seconds
    viewRequest.setPingUrl(pingURL);

    return viewRequest;
}
```

**`Node.js`**

```javascript title="Node.js"
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.
  // The query parameter is included as an example of how
  // to save/recover state information during the redirect to
  // the DocuSign signing. It's usually better to use
  // the session mechanism of your web framework. Query parameters
  // can be changed/spoofed very easily.
  viewRequest.returnUrl = args.dsReturnUrl + '?state=123';

  // 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"
$authentication_method = 'None'; # How is this application authenticating
# the signer? See the `authentication_method' definition
# https://developers.docusign.com/docs/esign-rest-api/reference/envelopes/envelopeviews/createrecipient/
$recipient_view_request = $clientService->getRecipientViewRequest(
    $authentication_method,
    $args["envelope_args"]
);
```

**`PowerShell`**

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

$json = [ordered]@{
    'returnUrl'            = 'http://httpbin.org/get';
    'authenticationMethod' = 'none';
    'email'                = $variables.SIGNER_EMAIL;
    'userName'             = $variables.SIGNER_NAME;
    'clientUserId'         = 1000
} | ConvertTo-Json -Compress
```

**`Python`**

```python title="Python"
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"]
)
```

**`Ruby`**

```ruby title="Ruby"
def make_recipient_view_request(signer_client_id, ds_return_url, ds_ping_url, signer_email, signer_name)
  view_request = DocuSign_eSign::RecipientViewRequest.new
  # 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.
  # The query parameter is included as an example of how
  # to save/recover state information during the redirect to
  # the Docusign signing. It's usually better to use
  # the session mechanism of your web framework. Query parameters
  # can be changed/spoofed very easily.
  view_request.return_url = "#{ds_return_url}?state=123"

  # How has your app authenticated the user? In addition to your app's
  # authentication, you can include authenticate steps from Docusign;
  # e.g., SMS authentication
  view_request.authentication_method = 'none'

  # Recipient information must match the embedded recipient info
  # that was used to create the envelope
  view_request.email = signer_email
  view_request.user_name = signer_name
  view_request.client_user_id = signer_client_id

  # 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
  view_request.ping_frequency = '600' # seconds
  # NOTE: The pings will only be sent if the pingUrl is an HTTPS address
  view_request.ping_url = ds_ping_url # Optional setting

  view_request
end
```

## Step 5. Create the recipient view and initiate embedded signing

Next, create the recipient view. Use the [EnvelopeViews:createRecipient](/docs/esign-rest-api/reference/envelopes/envelopeviews/createrecipient) method, passing in your API account ID and the `envelopeId` and `viewRequest` objects generated in previous steps.

Finally, extract the URL for embedded signing, which is the value of the `Url` key from the JSON response. You can redirect your app's internal browser to this URL to begin signing.

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

**`Bash`**

```bash title="Bash"
Status=$(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/${envelope_id}/views/recipient \
     --output ${response})
```

**`C#`**

```csharp title="C#"
RecipientViewRequest viewRequest = MakeRecipientViewRequest(signerEmail, signerName, returnUrl, signerClientId, pingUrl);

// call the CreateRecipientView API
var viewUrl = envelopesApi.CreateRecipientViewWithHttpInfo(accountId, envelopeId, viewRequest);
viewUrl.Headers.TryGetValue("X-RateLimit-Remaining", out remaining);
viewUrl.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);
}

// Don't use an iFrame!
// State can be stored/recovered using the framework's session or a
// query parameter on the returnUrl (see the makeRecipientViewRequest method)
string redirectUrl = viewUrl.Data.Url;

// returning both the envelopeId as well as the url to be used for embedded signing
return (envelopeId, redirectUrl);
```

**`Java`**

```java title="Java"
RecipientViewRequest viewRequest = EmbeddedSigningService.makeRecipientViewRequest(
        signerEmail,
        signerName,
        SIGNER_CLIENT_ID,
        config.getDsReturnUrl(),
        config.getDsPingUrl());

ViewUrl viewUrl = EmbeddedSigningService.embeddedSigning(
        apiClient,
        accountId,
        envelopeId,
        viewRequest
);

// Redirect the user to the embedded signing
// Don't use an iFrame!
// State can be stored/recovered using the framework's session or a
// query parameter on the returnUrl (see the makeRecipientViewRequest method)
return new RedirectView(viewUrl.getUrl());
```

**`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()}`);
    }
});

return { envelopeId: envelopeId, redirectUrl: results.data.url };
};
```

**`PHP`**

```php title="PHP"
$viewUrl = $clientService->getRecipientView($args['account_id'], $envelope_id, $recipient_view_request);
return ['envelope_id' => $envelope_id, 'redirect_url' => $viewUrl['url']];
```

**`PowerShell`**

```text title="PowerShell"
Invoke-RestMethod `
    -Uri "${apiUri}/v2.1/accounts/${accountId}/envelopes/${envelopeId}/views/recipient" `
    -Method 'POST' `
    -Headers @{
    'Authorization' = "Bearer $accessToken";
    'Content-Type'  = "application/json";
} `
    -Body $json `
    -OutFile $response

Write-Output "Response: $(Get-Content -Raw $response)"
$signingUrl = $(Get-Content $response | ConvertFrom-Json).url
```

**`Python`**

```python title="Python"
(data, 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": data.url}
```

**`Ruby`**

```ruby title="Ruby"
view_request = make_recipient_view_request(signer_client_id, ds_return_url, ds_ping_url, signer_email, signer_name)

# Call the CreateRecipientView API
results, _status, headers = envelope_api.create_recipient_view_with_http_info args[:account_id], envelope_id, 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

# Redirect the user to the embedded signing
# Don't use an iframe!
# State can be stored/recovered using the framework's session or a
# query parameter on the returnUrl (see the makeRecipientViewRequest method)
# Redirect to results.url
results.url
```

## Expected response

Use the return URL in the JSON response to start the embedded signing session in your browser.

**`Sample response`**

```json title="Sample response"
{
  "url": "https://demo.docusign.net/Signing/MTRedeem/v1/54984548-xxxx-xxxx-xxxx-cd0772818bbf?slt=eyJ0eX...m87j8w"
}
```

## 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 [Embedded signing and sending](/docs/esign-rest-api/esign101/concepts/embedding/embedded-signing).
* Learn [How to send an envelope via your app](/docs/esign-rest-api/how-to/embedded-sending).
* 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.