> 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 assign a form to a form group

> This topic demonstrates how to assign a form to a form group for your Docusign Rooms for Real Estate account.

Docusign Rooms for Real Estate only

This topic demonstrates how to assign a form to a [form group](/docs/rooms-api/rooms101/forms/managing-forms-rooms) for your Docusign Rooms for Real Estate account.

> **Warning**
>
> You must first [create a form group](/docs/rooms-api/how-to/create-form-group) and [grant office access to this form group](/docs/rooms-api/how-to/access-form-group) to complete this how-to.

> **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/v2 Where \<domain> is demo.rooms.docusign.com for the developer environment and rooms.docusign.com for production. |
| \{FORM_GROUP_ID}                    | A [GUID](http://guid.one/) value that identifies your form group. This value is created by Docusign when you [create a form group](/docs/rooms-api/how-to/create-form-group).                                                                                                                                 |
| \{FORM_ID}                          | A [GUID](http://guid.one/) value that identifies the form to attach to a room. To return a list of your form IDs, use the [FormLibraries:GetFormLibraries](/docs/rooms-api/reference/forms/formlibraries/getformlibraries) method.                                                                            |
| Forms enabled on your Rooms account | The user role needs the **Manage form groups** permission assigned. These permissions are only available to accounts with Forms enabled. To enable this feature, contact your Account Manager or Business Development representative.                                                                         |
| Rooms enabled for your account      | You will need access enabled to use the Rooms API. See [creating a Rooms developer account](/docs/rooms-api/rooms101/create-account).                                                                                                                                                                         |

## 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 [Authentication](/docs/rooms-api/rooms101/auth) for guidance on your options to get an OAuth token.

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

## Step 2. Construct your API headers

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

**`Bash`**

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

**`C#`**

```csharp title="C#"
var apiClient = new DocuSignClient(basePath);
apiClient.Configuration.DefaultHeader.Add("Authorization", $"Bearer {accessToken}");
```

**`Java`**

```java title="Java"
protected static ApiClient createApiClient(String basePath, String userAccessToken) {
    ApiClient apiClient = new ApiClient(basePath);
    apiClient.addDefaultHeader(HttpHeaders.AUTHORIZATION, BEARER_AUTHENTICATION + userAccessToken);
    apiClient.addAuthorization("docusignAccessCode", new OAuth());
    return apiClient;
}

/**
 * Creates a new instance of the RoomsApi. This method
 * creates an instance of the ApiClient class silently.
 *
 * @param basePath        URL to Rooms REST API
 * @param userAccessToken user's access token
 * @return an instance of the {@link RoomsApi}
 */
protected static RoomsApi createRoomsApiClient(String basePath, String userAccessToken) {
    ApiClient apiClient = createApiClient(basePath, userAccessToken);
    return new RoomsApi(apiClient);
}

/**
 * Creates a new instance of the rooms RolesApi. This method
 * creates an instance of the ApiClient class silently.
 *
 * @param basePath        URL to Rooms REST API
 * @param userAccessToken user's access token
 * @return an instance of the {@link RolesApi}
 */
protected static RolesApi createRolesApiClient(String basePath, String userAccessToken) {
    ApiClient apiClient = createApiClient(basePath, userAccessToken);
    return new RolesApi(apiClient);
}
```

**`Node.js`**

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

**`PHP`**

```php title="PHP"
$config = new Configuration();
$config->setHost('https://demo.rooms.docusign.com/restapi');
$config->addDefaultHeader('Authorization', 'Bearer ' . $args['ds_access_token']);
$this->apiClient = new ApiClient($config);
```

**`PowerShell`**

```text title="PowerShell"
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.add("Authorization", "Bearer $accessToken")
$headers.add("Accept", "application/json")
$headers.add("Content-Type", "application/json")
```

**`Python`**

```python title="Python"
api_client = create_rooms_api_client(access_token=args["access_token"])
```

**`Ruby`**

```ruby title="Ruby"
configuration = DocuSign_Rooms::Configuration.new
configuration.host = Rails.configuration.rooms_host

api_client = DocuSign_Rooms::ApiClient.new(configuration)
api_client.set_default_header('Authorization', "Bearer #{args[:access_token]}")
```

## Step 3. Retrieve the desired form library ID

Rooms accounts have forms bundled into objects known as [FormLibraries](/docs/rooms-api/reference/forms/formlibraries). Form Libraries are collections of form IDs that can be applied to a given form group through its associated form group ID.

Retrieve your desired form ID from the `formsLibraryId` by making a GET request to the [FormLibraries:GetFormLibraries](/docs/rooms-api/reference/forms/formlibraries/getformlibraries) endpoint. Here’s how you make the call, but make sure to substitute your base path for \{BASE_PATH} and API account ID for \{API_ACCOUNT_ID}.

**`Bash`**

```bash title="Bash"
# Create a temporary file to store the response
response=$(mktemp /tmp/response-rooms.XXXXXX)
# Call the Rooms API to look up your forms library ID
Status=$(curl -w '%{http_code}' --request GET ${base_path}/restapi/v2/accounts/${API_ACCOUNT_ID}/form_libraries "${Headers[@]}" --output ${response})

if [[ "$Status" -gt "200" ]]; then
    echo ""
    echo "Error:"
    echo ""
    cat $response
    exit 1
fi

echo ""
echo "Response:"
cat $response
echo ""

declare -A form_name_to_id_map
form_names=()
FORM_ID=''

FORMS_LIBRARY_ID=$(cat $response | grep formsLibraryId | sed 's/.*formsLibraryId\":"//' | sed 's/\".*//')

# Call the Rooms API to look up a list of form IDs for the given forms library
Status=$(curl -s -w '%{http_code}' --request GET ${base_path}/restapi/v2/accounts/${API_ACCOUNT_ID}/form_libraries/${FORMS_LIBRARY_ID}/forms "${Headers[@]}" --output ${response})

if [[ "$Status" -gt "200" ]]; then
    echo ""
    echo "Error:"
    echo ""
    cat $response
    exit 1
fi

form_name=`cat $response | grep -o -P '(?<=name\":\").*?(?=\")'`
form_ids=`cat $response | grep -o -P '(?<=libraryFormId\":).*?(?=\,)'`

arr_form_ids=($form_ids)
form_count=$(echo "$form_name" | grep -c '^')

if [ "$form_count" -eq "1" ]; then
    FORM_ID=$form_ids
else
    echo ""
    PS3='Select a form by the form name: '
    IFS=$'\n'
    select form in $form_name; do
        if [ "$REPLY" -gt "0" ] && [ "$REPLY" -le "$form_count" ]; then
            FORM_ID=${arr_form_ids[$REPLY-1]//\"/}
            break
        fi
    done
fi

echo ""
echo "FORM_ID: " $FORM_ID
echo ""
```

**`C#`**

```csharp title="C#"
ApiResponse<FormLibrarySummaryList> formLibraries = formLibrariesApi.GetFormLibrariesWithHttpInfo(accountId);

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

ApiResponse<FormSummaryList> forms = null;
if (formLibraries.Data.FormsLibrarySummaries.Any())
{
    forms = formLibrariesApi.GetFormLibraryFormsWithHttpInfo(
        accountId,
        formLibraries.Data.FormsLibrarySummaries.First().FormsLibraryId);
}

forms.Headers.TryGetValue("X-RateLimit-Remaining", out remaining);
forms.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"
List<FormSummary> forms = GetFormSummaryListService.getFormSummaryList(
        createFormLibrariesApi(session.getBasePath(), this.user.getAccessToken()),
        this.session.getAccountId());
```

**`Node.js`**

```javascript title="Node.js"
const formLibrariesApi = new docusignRooms.FormLibrariesApi(dsApiClient);
formLibraries = await new Promise((resolve, reject) => {
    formLibrariesApi.getFormLibraries(args.accountId,
      (err, data, response) => {
      if (err) return reject(err);
      resolve({ data, response });
    });
  });

  let headers = formLibraries.response.headers;
  let remaining = headers['x-ratelimit-remaining'];
  let 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()}`);
  }

const firstFormLibraryId = formLibraries.data.formsLibrarySummaries.find(lib => lib.formCount > 0).formsLibraryId;
```

**`PHP`**

```php title="PHP"
$forms = AssignFormToFormGroupService::getForms(
    $this->routerService,
    $this->clientService,
    $this->args,
    $this::EG
);

    /**
     * Get available forms
     *
     * @param $routerService
     * @param $clientService
     * @param $args
     * @param $eg
     * @return array
     */
    public static function getForms($routerService, $clientService, $args, $eg): array
    {
$forms = [];
$libraries = AssignFormToFormGroupService::getFormLibraries(
    $routerService,
    $clientService,
    $args,
    $eg
);
if (count($libraries)) {
    $forms = AssignFormToFormGroupService::getFormLibraryForms(
        $libraries[0]['forms_library_id'],
        $routerService,
        $clientService,
        $args,
        $eg
    );
}
return $forms;
    }

    /**
     * Get Form Libraries
     *
     * @param $routerService
     * @param $clientService
     * @param $args
     * @param $eg
     * @return array
     */
    public static function getFormLibraries($routerService, $clientService, $args, $eg): array
    {
$minimum_buffer_min = 3;
if ($routerService->dsTokenOk($minimum_buffer_min)) {
    return $clientService->getFormLibraries($args);
} else {
    $clientService->needToReAuth($eg);
}
    }

    /**
     * Get available Forms
     *
     * @param string $libraryID
     * @param $routerService
     * @param $clientService
     * @param $args
     * @param $eg
     * @return array
     */
    public static function getFormLibraryForms(string $libraryID, $routerService, $clientService, $args, $eg): array
    {
$minimum_buffer_min = 3;
if ($routerService->dsTokenOk($minimum_buffer_min)) {
    return $clientService->getFormLibraryForms($libraryID, $args['account_id']);
} else {
    $clientService->needToReAuth($eg);
}
    }
```

**`PowerShell`**

```text title="PowerShell"
$base_path = "https://demo.rooms.docusign.com"
$uri = "$base_path/restapi/v2/accounts/$APIAccountId/form_libraries"
try {
    Write-Output "Response:"
    $response = Invoke-WebRequest -uri $uri -headers $headers -method GET
    $response.Content
    # Retrieve a form library ID
    $obj = $response.Content | ConvertFrom-Json
    $formsLibraryID = $obj.formsLibrarySummaries[0].formsLibraryId
} catch {
    Write-Output "Unable to retrieve form library"
    # On failure, display a notification, X-DocuSign-TraceToken, error message, and the command that triggered the error

    foreach ($header in $_.Exception.Response.Headers) {
        if ($header -eq "X-DocuSign-TraceToken") { Write-Output "TraceToken : " $_.Exception.Response.Headers[$int] }
        $int++
    }
    Write-Output "Error : "$_.ErrorDetails.Message
    Write-Output "Command : "$_.InvocationInfo.Line
}

# Call the Rooms API to look up a list of form IDs for the given forms library
$uri = "$base_path/restapi/v2/accounts/$APIAccountId/form_libraries/$formsLibraryID/forms"

try {
    Write-Output ""
    Write-Output "Response:"
    $response = Invoke-WebRequest -uri $uri -headers $headers -method GET
    $response.Content

    $formsObj = $($response.Content  | ConvertFrom-Json).forms

    Write-Output ""
    $menu = @{}
    for ($i=1;$i -le $formsObj.count; $i++) {
        Write-Output "$i. $($formsObj[$i-1].name)"
        $menu.Add($i,($formsObj[$i-1].libraryFormId))
    }

    do {
        Write-Output ""
        [int]$selection = Read-Host 'Select a form by the form name: '
    } while ($selection -gt $formsObj.count -or $selection -lt 1);
    $formID = $menu.Item($selection)

    Write-Output ""
    Write-Output "Form Id: $formID"
} catch {
    Write-Output "Unable to retrieve a form id"
    # On failure, display a notification, X-DocuSign-TraceToken, error message, and the command that triggered the error

    foreach ($header in $_.Exception.Response.Headers) {
        if ($header -eq "X-DocuSign-TraceToken") { Write-Output "TraceToken : " $_.Exception.Response.Headers[$int] }
        $int++
    }
    Write-Output "Error : "$_.ErrorDetails.Message
    Write-Output "Command : "$_.InvocationInfo.Line
}
```

**`Python`**

```python title="Python"
form_libraries_api = FormLibrariesApi(api_client)
(form_libraries, status, headers) = form_libraries_api.get_form_libraries_with_http_info(
    account_id=args["account_id"]
)

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

first_form_library_id = form_libraries.forms_library_summaries[0].forms_library_id

# Get forms
(form_library_forms, status, headers) = form_libraries_api.get_form_library_forms_with_http_info(
    form_library_id=first_form_library_id, account_id=args["account_id"]
)   # type: FormSummaryList

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

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

**`Ruby`**

```ruby title="Ruby"
@forms = RoomApi::GetDataService.new(session).get_form_libraries
```

## Step 4. Select a form group ID

To find the form group you want to assign the form to, you need to make a GET request to the [FormGroups:GetFormGroups](/docs/rooms-api/reference/forms/formgroups/getformgroups) endpoint. The Rooms API will return a list of available form group IDs; select one to continue through the example.

Here’s how you make the call, but make sure to substitute your base path for \{BASE_PATH} and API account ID for \{API_ACCOUNT_ID}.

**`Bash`**

```bash title="Bash"
# Call the Rooms API to look up a list of form group IDs
Status=$(curl -w '%{http_code}' --request GET ${base_path}/restapi/v2/accounts/${API_ACCOUNT_ID}/form_groups "${Headers[@]}" --output ${response})

if [[ "$Status" -gt "200" ]]; then
    echo ""
    echo "Error:"
    echo ""
    cat $response
    exit 1
fi

echo ""
echo "Response:"
cat $response
echo ""

form_group_name=`cat $response | grep -o -P '(?<=name\":\").*?(?=\")'`

form_group_ids=`cat $response | grep -o -P '(?<=formGroupId\":).*?(?=\,)'`

arr_form_group_ids=($form_group_ids)
form_group_count=$(echo "$form_group_name" | grep -c '^')

if [ -z "$form_group_name" ]; then
    echo ""
    echo "Error:"
    echo ""
    echo "Form group ID is needed. Please run step 7 - Create a form group..."
    exit 0
elif [ "$form_count" -eq "1" ]; then
    FORM_GROUP_ID=$form_group_ids
else
    echo ""
    PS3="Select a form group: "
    IFS=$'\n'
    select form_group in $form_group_name; do
        if [ "$REPLY" -gt "0" ] && [ "$REPLY" -le "$form_group_count" ]; then
            FORM_GROUP_ID=${arr_form_group_ids[$REPLY-1]//\"/}
            break
        fi
    done
fi
```

**`C#`**

```csharp title="C#"
ApiResponse<FormGroupSummaryList> formGroups = formGroupsApi.GetFormGroupsWithHttpInfo(accountId);
```

**`Java`**

```java title="Java"
this.formGroupsApi = createFormGroupsApi(
        this.session.getBasePath(), this.user.getAccessToken()
);
FormGroupSummaryList formGroupSummaryList = formGroupsApi.getFormGroups(this.session.getAccountId());
```

**`Node.js`**

```javascript title="Node.js"
const formsGroupsApi = new docusignRooms.FormGroupsApi(dsApiClient);
  response = await new Promise((resolve, reject) => {
    formsGroupsApi.getFormGroups(args.accountId,
      (err, data, response) => {
      if (err) return reject(err);
      resolve({ data, response });
    });
  });

  let headers = response.response.headers;
  let remaining = headers['x-ratelimit-remaining'];
  let 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"
$formGroups = AssignFormToFormGroupService::getFormGroups(
    $this->routerService,
    $this->clientService,
    $this->args,
    $this::EG
);
parent::controller(null, null, $forms, null, $formGroups);
    /**
     * Get available form groups
     *
     * @param $routerService
     * @param $clientService
     * @param $args
     * @param $eg
     * @return array
     */
    public static function getFormGroups($routerService, $clientService, $args, $eg): array
    {
$minimum_buffer_min = 3;
$formGroups = [];
if ($routerService->dsTokenOk($minimum_buffer_min)) {
    $formGroups = $clientService->getFormGroups($args['account_id']);
} else {
    $clientService->needToReAuth($eg);
}
return $formGroups;
    }
```

**`PowerShell`**

```text title="PowerShell"
$formGroupID = ""

# Call the Rooms API to look up a list of form group IDs
$uri = "${base_path}/restapi/v2/accounts/$APIAccountId/form_groups"
$result = Invoke-WebRequest -uri $uri -UseBasicParsing -headers $headers -method GET

Write-Output ""
Write-Output "Response:"
$result.Content

$formGroupObj = $($result.Content  | ConvertFrom-Json).formGroups
Write-Output ""

# Setup a temporary menu option to pick a form group
$menu = @{}
for ($i=1;$i -le $formGroupObj.count; $i++) {
    Write-Output "$i. $($formGroupObj[$i-1].name)"
    $menu.Add($i,($formGroupObj[$i-1].formGroupId))
}

if ($formGroupObj.count -lt 1) {
   Write-Output "A form group ID is needed. Fix: execute code example 7 - Create a form group..."
   exit 1
}

do {
    Write-Output ""
    [int]$selection = Read-Host 'Select a form group: '
} while ($selection -gt $formGroupObj.count -or $selection -lt 1);
$formGroupID = $menu.Item($selection)

Write-Output ""
Write-Output "Form group Id: $formGroupID"
Write-Output ""
```

**`Python`**

```python title="Python"
form_groups_api = FormGroupsApi(api_client)
(response, status, headers) = form_groups_api.get_form_groups_with_http_info(
    account_id=args["account_id"]
)  # type: FormGroupSummaryList

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

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

**`Ruby`**

```ruby title="Ruby"
@form_groups = RoomApi::GetDataService.new(session).get_form_groups
```

## Step 5. Construct your request body

Next, create a request body using the previously obtained form ID. Make sure to substitute your form ID for \{FORM_ID}.

**`Bash`**

```bash title="Bash"
printf \
    '
{
  "formId": "'"${FORM_ID}"'",
}' >>$request_data
```

**`C#`**

```csharp title="C#"
var form = new FormGroupFormToAssign() { FormId = formFormGroupModel.FormId };
```

**`Java`**

```java title="Java"
FormGroupFormToAssign formGroupFormToAssignRequest = new FormGroupFormToAssign()
        .formId(formId);
```

**`Node.js`**

```javascript title="Node.js"
const formGroupToAssign =
  new docusignRooms.FormGroupFormToAssign.constructFromObject({
    formId: args.formId,
    isRequired: true,
  });
```

**`PHP`**

```php title="PHP"
$form_group_form_to_assign = new FormGroupFormToAssign(['form_id' => $args['form_id']]);
```

**`PowerShell`**

```text title="PowerShell"
$body =
@"
 {"formId": "$formID" }
"@
```

**`Python`**

```python title="Python"
form_group_to_assign = FormGroupFormToAssign(
    form_id=args["form_id"], is_required=True
)
```

**`Ruby`**

```ruby title="Ruby"
DocuSign_Rooms::FormGroupFormToAssign.new(
  {
    formId: args[:form_id]
  }
)
```

## Step 6. Call the Rooms API

Now that you have constructed your API headers and request body, make a POST request to the [FormGroups:AssignFormGroupForm](/docs/rooms-api/reference/forms/formgroups/assignformgroupform)   endpoint and include the request body to add your form to a form group for your Rooms account.

Here’s how you make the call, but make sure to substitute your base path for \{BASE_PATH}, API account ID for \{API_ACCOUNT_ID}, and form group ID for \{FORM_GROUP_ID}.

> **Note**
>
> View the source code for this how-to on GitHub: [Bash](https://github.com/docusign/code-examples-bash/blob/master/examples/Rooms/eg009AssignFormGroup.sh), [C#](https://github.com/docusign/code-examples-csharp/blob/master/launcher-csharp/Rooms/Examples/AssignFormToFormGroups.cs), [Java](https://github.com/docusign/code-examples-java/blob/master/src/main/java/com/docusign/controller/rooms/examples/R009ControllerAssignFormToFormGroup.java), [Node](https://github.com/docusign/code-examples-node/blob/master/lib/rooms/examples/assignFormToFormGroup.js), [PHP](https://github.com/docusign/code-examples-php/blob/master/src/Services/Examples/Rooms/AssignFormToFormGroupService.php), [PowerShell](https://github.com/docusign/code-examples-powershell/blob/master/examples/Rooms/eg009AssignFormGroup.ps1), [Python](https://github.com/docusign/code-examples-python/blob/master/app/rooms/examples/eg009_assign_form_to_form_group.py), or [Ruby](https://github.com/docusign/code-examples-ruby/blob/main/app/services/room_api/eg009_assign_form_to_form_group_service.rb).

**`Bash`**

```bash title="Bash"
Status=$(curl -w '%{http_code}' --request POST ${base_path}/restapi/v2/accounts/${API_ACCOUNT_ID}/form_groups/${FORM_GROUP_ID}/assign_form "${Headers[@]}" --data-binary @${request_data} --output ${response})
```

**`C#`**

```csharp title="C#"
var response = formGroupsApi.AssignFormGroupFormWithHttpInfo(accountId, new Guid(formGroupId), formToAssign);

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

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

return response.Data;
```

**`Java`**

```java title="Java"
FormGroupFormToAssign formGroupFormToAssign = AssignFormToFormGroupService.assignFormToFormGroup(
        this.formGroupsApi,
        this.session.getAccountId(),
        args.getFormId(),
        args.getFormGroupId());
```

**`Node.js`**

```javascript title="Node.js"
const formsGroupsApi = new docusignRooms.FormGroupsApi(dsApiClient);
results = await new Promise((resolve, reject) => {
    formsGroupsApi.assignFormGroupForm(
      args.accountId,
      args.formGroupId,
      {
        body: formGroupToAssign,
      },
      (err, data, response) => {
      if (err) return reject(err);
      resolve({ data, response });
    });
  });

  headers = results.response.headers;
  remaining = headers['x-ratelimit-remaining'];
  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"
$form_api = $clientService->getFromGroupsApi();
$formGroupResult = $form_api->assignFormGroupFormWithHttpInfo(
    $args['form_group_id'],
    $args["account_id"],
    $form_group_form_to_assign
);

$remaining = $response[2]['x-ratelimit-remaining'] ?? null;
$reset = $response[2]['x-ratelimit-reset'] ?? null;

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

**`PowerShell`**

```text title="PowerShell"
$uri = "$base_path/restapi/v2/accounts/$APIAccountId/form_groups/$formGroupID/assign_form"

try {
    $response = Invoke-WebRequest -uri $uri -headers $headers -method POST -Body $body
    Write-Output $response.Status
    Write-Output "Response: No JSON response body returned when setting the default office ID in a form group"
} catch {
    Write-Output "Unable to assign the form to the form group"
    # On failure, display a notification, X-DocuSign-TraceToken, error message, and the command that triggered the error

    foreach ($header in $_.Exception.Response.Headers) {
        if ($header -eq "X-DocuSign-TraceToken") { Write-Output "TraceToken : " $_.Exception.Response.Headers[$int] }
        $int++
    }
    Write-Output "Error : "$_.ErrorDetails.Message
    Write-Output "Command : "$_.InvocationInfo.Line
}
```

**`Python`**

```python title="Python"
(response, status, headers) = form_groups_api.assign_form_group_form_with_http_info(
    form_group_id=args["form_group_id"], account_id=args["account_id"],
    body=form_group_to_assign
)   # type: FormGroupFormToAssign

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

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

**`Ruby`**

```ruby title="Ruby"
form_groups_api = DocuSign_Rooms::FormGroupsApi.new(api_client)
begin
  response, _status, headers = form_groups_api.assign_form_group_form_with_http_info(args[:form_group_id], args[:account_id], body(args))

  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
rescue Exception
  return { exception: 'Failed to assign a form to a form group' }
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"
{
  "formGroupId": "05e4c7a9-xxxx-xxxx-xxxx-b3e9b55b0e55",
  "name": "Sample Room Form Group",
  "officeIds": [
    "4xxx1"
  ],
  "forms": [
    {
      "formId": "24416d38-xxxx-xxxx-xxxx-a19720cc2931",
      "name": "DUPLICATE FIELD FORM - DTRENG-1984",
      "isRequired": false,
      "lastUpdatedDate": "2020-07-31T23:21:04.027"
    }
  ]
}
```

## Next steps

* Run this code example from our [Quickstart](/docs/esign-rest-api/quickstart) or launcher projects:    [Bash](https://github.com/docusign/code-examples-bash), [C#](https://github.com/docusign/code-examples-csharp), [Java](https://github.com/docusign/code-examples-java), [Node.js](https://github.com/docusign/code-examples-node), [PHP](https://github.com/docusign/code-examples-php), [PowerShell](https://github.com/docusign/code-examples-powershell), [Python](https://github.com/docusign/code-examples-python), or [Ruby](https://github.com/docusign/code-examples-ruby).
* Learn [Rooms concepts](/docs/rooms-api/rooms101/concepts).
* See all available Rooms API [How-to guides](/docs/rooms-api/how-to).
* See details about [Using room templates and task lists](/docs/rooms-api/rooms101/templates).
* See how to [Go-Live](/docs/rooms-api/go-live)  with a completed app and find the base path for API calls in the production environment.