> ## Documentation Index
> Fetch the complete documentation index at: https://help.dingtalk.io/llms.txt
> Use this file to discover all available pages before exploring further.

# ブロック要素を挿入する

> ドキュメント内の任意の位置にブロック要素を追加し、プログラムからコンテンツを管理します

このAPIを呼び出すと、指定した位置にブロック要素を1つ挿入できます。

## API 呼び出し説明

ドキュメントのコンテンツに関するデータ構造の詳細については、[ドキュメントデータ構造](/ja/open/development/document-data-structure)をご参照ください。

## リクエスト

### 基本情報

| フィールド        | 値                                                                   |
| ------------ | ------------------------------------------------------------------- |
| HTTP URL     | `https://api.dingtalk.io/v1.0/doc/suites/documents/{docKey}/blocks` |
| HTTP Method  | POST                                                                |
| サポートするアプリタイプ | appType-社内アプリ                                                       |
| 必要な権限        | permission-Storage.File.Write-企業ストレージファイル書き込み権限                     |

### リクエストヘッダー

| 名前                          | タイプ    | 必須 | 説明                                                                                                                            |
| --------------------------- | ------ | -- | ----------------------------------------------------------------------------------------------------------------------------- |
| x-acs-dingtalk-access-token | String | はい | このAPIを呼び出すためのアクセス認証情報です。[社内アプリのアクセストークンを取得する](/ja/open/development/obtain-the-access-token-of-an-internal-app)APIを呼び出して取得します。 |

### パスパラメータ

| 名前     | タイプ    | 必須 | 説明                                                                                                                                                                                                                                                                                                                            |
| ------ | ------ | -- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| docKey | String | はい | ドキュメントID（ドキュメントの docKey または dentryUuid）です。[ナレッジベースドキュメントを作成する](/ja/open/development/create-team-space-document)APIでドキュメントを作成した後、レスポンスから `docKey` パラメータを取得します。      `dentryUuid` はドキュメントURLから取得します。例えば [https://docs.dingtalk.io/i/nodes/Zxxxxa-id](https://docs.dingtalk.io/i/nodes/Zxxxxa-id) の場合、dentryUuid は Zxxxxa-id です。 |

### クエリパラメータ

| 名前         | タイプ    | 必須 | 説明                                                                                                     |
| ---------- | ------ | -- | ------------------------------------------------------------------------------------------------------ |
| operatorId | String | はい | ユーザーのunionIdです。[ユーザー詳細を照会する](/ja/open/development/query-user-details)APIを呼び出して unionid パラメータの値を取得できます。 |

### リクエストボディ

| 名前      | タイプ                | 必須  | 説明                                                                                                                                                                                                                      |
| ------- | ------------------ | --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| blockId | String             | いいえ | 対象 Block の一意な識別子です。[ブロック要素を照会する](/ja/open/development/api-docblocksquery)APIを呼び出して `blockId` パラメータを取得できます。未入力の場合は index が使用されます。                                                                                        |
| index   | Integer            | いいえ | `blockId` が存在しない場合、`index` を使用してドキュメントの `index` 番目のトップレベルブロック要素を対象位置として検索します。`index` は 0 から始まります。      未入力の場合、デフォルトでドキュメントの末尾になります。                                                                                     |
| where   | String             | いいえ | 対象位置の前後どちらに挿入するかを指定します。値:   - **after**: 対象位置の後ろに挿入します（デフォルト値）。 - **before**: 対象位置の前に挿入します。                                                                                                                             |
| element | `Map<String, Any>` | はい  | 挿入する BlockElement のタイプと、対応するタイプを作成するために必要な属性です（詳細は[ブロック要素データ構造](/ja/open/development/block-data-structure)をご参照ください）。構造は次のとおりです:   `{   "blockType": enum(BlockType),   [blockType]: Object(CreateElementProperties), }` |
|         | Any                | いいえ | 要素タイプおよびその要素を作成するために必要な情報を含みます。                                                                                                                                                                                         |

### リクエスト例

HTTP

```http theme={"theme":{"light":"github-light","dark":"github-dark"}}
POST /v1.0/doc/suites/documents/doc_id/blocks?operatorId=union_id HTTP/1.1
Host:api.dingtalk.io
x-acs-dingtalk-access-token:7dc9ec4xxx
Content-Type:application/json

{
  "blockId" : "block_id",
  "index" : 1,
  "where" : "after",
  "element" : {
    "blockType" : "paragraph",
    "paragraph" : {
      "text" : "foo"
    }
  }
}
```

Java

```java theme={"theme":{"light":"github-light","dark":"github-dark"}}
package com.aliyun.sample;

import com.aliyun.tea.*;

public class Sample {

    /**
     * <b>description</b> :
     * <p>Token を使用してアカウント Client を初期化します</p>
     * @return Client
     * 
     * @throws Exception
     */
    public static com.aliyun.dingtalkdoc_1_0.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkdoc_1_0.Client(config);
    }

    public static void main(String[] args_) throws Exception {
        
        com.aliyun.dingtalkdoc_1_0.Client client = Sample.createClient();
        com.aliyun.dingtalkdoc_1_0.models.DocInsertBlocksHeaders docInsertBlocksHeaders = new com.aliyun.dingtalkdoc_1_0.models.DocInsertBlocksHeaders();
        docInsertBlocksHeaders.xAcsDingtalkAccessToken = "<your access token>";
        java.util.Map<String, java.util.Map<String, Object>> element = TeaConverter.buildMap(
            new TeaPair("key", new java.util.HashMap<>())
        );
        com.aliyun.dingtalkdoc_1_0.models.DocInsertBlocksRequest docInsertBlocksRequest = new com.aliyun.dingtalkdoc_1_0.models.DocInsertBlocksRequest()
                .setOperatorId("union_id")
                .setBlockId("block_id")
                .setIndex(1)
                .setWhere("after")
                .setElement(element);
        try {
            client.docInsertBlocksWithOptions("doc_id", docInsertBlocksRequest, docInsertBlocksHeaders, new com.aliyun.teautil.models.RuntimeOptions());
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err には code と message プロパティが含まれ、開発時の問題特定に役立ちます
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err には code と message プロパティが含まれ、開発時の問題特定に役立ちます
            }

        }        
    }
}
```

Python

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
import os
import sys
import json

from typing import List

from alibabacloud_dingtalk.doc_1_0.client import Client as dingtalkdoc_1_0Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dingtalk.doc_1_0 import models as dingtalkdoc__1__0_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient

class Sample:
    def __init__(self):
        pass

    @staticmethod
    def create_client() -> dingtalkdoc_1_0Client:
        """
        Token を使用してアカウント Client を初期化します
        @return: Client
        @throws Exception
        """
        config = open_api_models.Config()
        config.protocol = 'https'
        config.region_id = 'central'
        return dingtalkdoc_1_0Client(config)

    @staticmethod
    def main(
        args: List[str],
    ) -> None:
        client = Sample.create_client()
        doc_insert_blocks_headers = dingtalkdoc__1__0_models.DocInsertBlocksHeaders()
        doc_insert_blocks_headers.x_acs_dingtalk_access_token = '<your access token>'
        element = {
            'key': {}
        }
        doc_insert_blocks_request = dingtalkdoc__1__0_models.DocInsertBlocksRequest(
            operator_id='union_id',
            block_id='block_id',
            index=1,
            where='after',
            element=element
        )
        try:
            client.doc_insert_blocks_with_options('doc_id', doc_insert_blocks_request, doc_insert_blocks_headers, util_models.RuntimeOptions())
        except Exception as err:
            if not UtilClient.empty(err.code) and not UtilClient.empty(err.message):
                # err には code と message プロパティが含まれ、開発時の問題特定に役立ちます
                pass

    @staticmethod
    async def main_async(
        args: List[str],
    ) -> None:
        client = Sample.create_client()
        doc_insert_blocks_headers = dingtalkdoc__1__0_models.DocInsertBlocksHeaders()
        doc_insert_blocks_headers.x_acs_dingtalk_access_token = '<your access token>'
        element = {
            'key': {}
        }
        doc_insert_blocks_request = dingtalkdoc__1__0_models.DocInsertBlocksRequest(
            operator_id='union_id',
            block_id='block_id',
            index=1,
            where='after',
            element=element
        )
        try:
            await client.doc_insert_blocks_with_options_async('doc_id', doc_insert_blocks_request, doc_insert_blocks_headers, util_models.RuntimeOptions())
        except Exception as err:
            if not UtilClient.empty(err.code) and not UtilClient.empty(err.message):
                # err には code と message プロパティが含まれ、開発時の問題特定に役立ちます
                pass

if __name__ == '__main__':
    Sample.main(sys.argv[1:])
```

PHP

```java theme={"theme":{"light":"github-light","dark":"github-dark"}}
<?php

// This file is auto-generated, don't edit it. Thanks.
namespace AlibabaCloud\SDK\Sample;

use AlibabaCloud\SDK\Dingtalk\Vdoc_1_0\Dingtalk;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dingtalk\Vdoc_1_0\Models\DocInsertBlocksHeaders;
use AlibabaCloud\SDK\Dingtalk\Vdoc_1_0\Models\DocInsertBlocksRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

class Sample {

    /**
     * Token を使用してアカウント Client を初期化します
     * @return Dingtalk Client
     */
    public static function createClient(){
        $config = new Config([]);
        $config->protocol = "https";
        $config->regionId = "central";
        return new Dingtalk($config);
    }

    /**
     * @param string[] $args
     * @return void
     */
    public static function main($args){
        $client = self::createClient();
        $docInsertBlocksHeaders = new DocInsertBlocksHeaders([]);
        $docInsertBlocksHeaders->xAcsDingtalkAccessToken = "<your access token>";
        $element = [
            "key" => []
        ];
        $docInsertBlocksRequest = new DocInsertBlocksRequest([
            "operatorId" => "union_id",
            "blockId" => "block_id",
            "index" => 1,
            "where" => "after",
            "element" => $element
        ]);
        try {
            $client->docInsertBlocksWithOptions("doc_id", $docInsertBlocksRequest, $docInsertBlocksHeaders, new RuntimeOptions([]));
        }
        catch (Exception $err) {
            if (!($err instanceof TeaError)) {
                $err = new TeaError([], $err->getMessage(), $err->getCode(), $err);
            }
            if (!Utils::empty_($err->code) && !Utils::empty_($err->message)) {
                // err には code と message プロパティが含まれ、開発時の問題特定に役立ちます
            }
        }
    }
}
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
    require_once $path;
}
Sample::main(array_slice($argv, 1));
```

Go

```go theme={"theme":{"light":"github-light","dark":"github-dark"}}
package main

import (
  "encoding/json"
  "strings"
  "fmt"
  "os"
  util  "github.com/alibabacloud-go/tea-utils/v2/service"
  dingtalkdoc_1_0  "github.com/alibabacloud-go/dingtalk/doc_1_0"
  openapi  "github.com/alibabacloud-go/darabonba-openapi/v2/client"
  "github.com/alibabacloud-go/tea/tea"
)

// Description:
// 
// Token を使用してアカウント Client を初期化します
// 
// @return Client
// 
// @throws Exception
func CreateClient () (_result *dingtalkdoc_1_0.Client, _err error) {
  config := &openapi.Config{}
  config.Protocol = tea.String("https")
  config.RegionId = tea.String("central")
  _result = &dingtalkdoc_1_0.Client{}
  _result, _err = dingtalkdoc_1_0.NewClient(config)
  return _result, _err
}

func _main (args []*string) (_err error) {
  client, _err := CreateClient()
  if _err != nil {
    return _err
  }

  docInsertBlocksHeaders := &dingtalkdoc_1_0.DocInsertBlocksHeaders{}
  docInsertBlocksHeaders.XAcsDingtalkAccessToken = tea.String("<your access token>")
  element := map[string]map[string]interface{}{
    "key": map[string]interface{}{},
  }
  docInsertBlocksRequest := &dingtalkdoc_1_0.DocInsertBlocksRequest{
    OperatorId: tea.String("union_id"),
    BlockId: tea.String("block_id"),
    Index: tea.Int32(1),
    Where: tea.String("after"),
    Element: element,
  }
  tryErr := func()(_e error) {
    defer func() {
      if r := tea.Recover(recover()); r != nil {
        _e = r
      }
    }()
    _, _err = client.DocInsertBlocksWithOptions(tea.String("doc_id"), docInsertBlocksRequest, docInsertBlocksHeaders, &util.RuntimeOptions{})
    if _err != nil {
      return _err
    }

    return nil
  }()

  if tryErr != nil {
    var err = &tea.SDKError{}
    if _t, ok := tryErr.(*tea.SDKError); ok {
      err = _t
    } else {
      err.Message = tea.String(tryErr.Error())
    }
    if !tea.BoolValue(util.Empty(err.Code)) && !tea.BoolValue(util.Empty(err.Message)) {
      // err には code と message プロパティが含まれ、開発時の問題特定に役立ちます
    }

  }
  return _err
}

func main() {
  err := _main(tea.StringSlice(os.Args[1:]))
  if err != nil {
    panic(err)
  }
}
```

Node.js

```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
'use strict';
// This file is auto-generated, don't edit it
const Util = require('@alicloud/tea-util');
const dingtalkdoc_1_0 = require('@alicloud/dingtalk/doc_1_0');
const OpenApi = require('@alicloud/openapi-client');
const Tea = require('@alicloud/tea-typescript');

class Client {

  /**
   * Token を使用してアカウント Client を初期化します
   * @return Client
   * @throws Exception
   */
  static createClient() {
    let config = new OpenApi.Config({ });
    config.protocol = 'https';
    config.regionId = 'central';
    return new dingtalkdoc_1_0.default(config);
  }

  static async main(args) {
    let client = Client.createClient();
    let docInsertBlocksHeaders = new dingtalkdoc_1_0.DocInsertBlocksHeaders({ });
    docInsertBlocksHeaders.xAcsDingtalkAccessToken = '<your access token>';
    let element = {
      key: { },
    };
    let docInsertBlocksRequest = new dingtalkdoc_1_0.DocInsertBlocksRequest({
      operatorId: 'union_id',
      blockId: 'block_id',
      index: 1,
      where: 'after',
      element: element,
    });
    try {
      await client.docInsertBlocksWithOptions('doc_id', docInsertBlocksRequest, docInsertBlocksHeaders, new Util.RuntimeOptions({ }));
    } catch (err) {
      if (!Util.default.empty(err.code) && !Util.default.empty(err.message)) {
        // err には code と message プロパティが含まれ、開発時の問題特定に役立ちます
      }

    }    
  }

}

exports.Client = Client;
Client.main(process.argv.slice(2));
```

C#

```java theme={"theme":{"light":"github-light","dark":"github-dark"}}
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

using Tea;
using Tea.Utils;

namespace AlibabaCloud.SDK.Sample
{
    public class Sample 
    {

        /// <term><b>Description:</b></term>
        /// <description>
        /// <para>Token を使用してアカウント Client を初期化します</para>
        /// </description>
        /// 
        /// <returns>
        /// Client
        /// </returns>
        /// 
        /// <term><b>Exception:</b></term>
        /// Exception
        public static AlibabaCloud.SDK.Dingtalkdoc_1_0.Client CreateClient()
        {
            AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config();
            config.Protocol = "https";
            config.RegionId = "central";
            return new AlibabaCloud.SDK.Dingtalkdoc_1_0.Client(config);
        }

        public static void Main(string[] args)
        {
            AlibabaCloud.SDK.Dingtalkdoc_1_0.Client client = CreateClient();
            AlibabaCloud.SDK.Dingtalkdoc_1_0.Models.DocInsertBlocksHeaders docInsertBlocksHeaders = new AlibabaCloud.SDK.Dingtalkdoc_1_0.Models.DocInsertBlocksHeaders();
            docInsertBlocksHeaders.XAcsDingtalkAccessToken = "<your access token>";
            Dictionary<string, Dictionary<string, object>> element = new Dictionary<string, Dictionary<string, object>>
            {
                {"key", new Dictionary<string, object>(){}},
            };
            AlibabaCloud.SDK.Dingtalkdoc_1_0.Models.DocInsertBlocksRequest docInsertBlocksRequest = new AlibabaCloud.SDK.Dingtalkdoc_1_0.Models.DocInsertBlocksRequest
            {
                OperatorId = "union_id",
                BlockId = "block_id",
                Index = 1,
                Where = "after",
                Element = element,
            };
            try
            {
                client.DocInsertBlocksWithOptions("doc_id", docInsertBlocksRequest, docInsertBlocksHeaders, new AlibabaCloud.TeaUtil.Models.RuntimeOptions());
            }
            catch (TeaException err)
            {
                if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message))
                {
                    // err には code と message プロパティが含まれ、開発時の問題特定に役立ちます
                }
            }
            catch (Exception _err)
            {
                TeaException err = new TeaException(new Dictionary<string, object>
                {
                    { "message", _err.Message }
                });
                if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message))
                {
                    // err には code と message プロパティが含まれ、開発時の問題特定に役立ちます
                }
            }
        }

    }
}
```

## レスポンス

### レスポンスボディ

| 名前      | タイプ                | 説明                   |
| ------- | ------------------ | -------------------- |
| success | Boolean            | リクエストが成功したかどうかを示します。 |
| result  | Object             | リクエスト結果。             |
| data    | `Map<String, Any>` | 挿入された要素。             |
|         | Any                | 当該要素の具体的な情報。         |

### レスポンスボディ例

```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
HTTP/1.1 200 OK
Content-Type:application/json

{
  "success": true,
  "result": {
    "data": {
      "blockType": "paragraph",
      "paragraph": {
        "text": "foo"
      },
      "id": "lmoasis2f3wxmwyyyy",
      "index": 2,
    }
  }
}
```

### エラーコード

このAPIを呼び出してエラーが発生した場合は、エラーメッセージをもとに[グローバルエラーコード](/ja/open/development/server-api-error-codes-1)ドキュメントで解決方法をご確認ください。

| HttpCode | エラーコード                           | エラーメッセージ      | 説明                                                              |
| -------- | -------------------------------- | ------------- | --------------------------------------------------------------- |
| 400      | paramError                       | %s            | パラメータエラー                                                        |
| 400      | invalidRequest.inputArgs.invalid | %s            | パラメータエラーです。エラーメッセージをご確認ください。                                    |
| 403      | forbidden.accessDenied           | %s            | 権限がありません                                                        |
| 403      | forbidden.acrossOrg              | %s            | リクエストが不正です。アクセスするドキュメントが access\_token で指定された組織に所属しているかご確認ください。 |
| 404      | docNotExist                      | %s            | ドキュメントが存在しません                                                   |
| 404      | invalidRequest.resource.notFound | %s            | アクセス対象のリソースが見つかりません                                             |
| 500      | forbidden.operationIllegal       | %s            | リクエスト操作が不正です                                                    |
| 500      | systemError                      | %s            | サービスが混雑しています。後で再試行してください                                        |
| 500      | unknownError                     | Unknown Error | 不明なエラー                                                          |
| 503      | operationTimeout                 | %s            | リクエストがタイムアウトしました                                                |
