> ## Documentation Index
> Fetch the complete documentation index at: https://docs-dev-actions-triggers-prototype.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 一括ユーザーインポート

> Management APIを使用して一括ユーザーインポートを行う方法について説明します。

export const AuthCodeGroup = ({children, dropdown}) => {
  const [processedChildren, setProcessedChildren] = useState(children);
  useEffect(() => {
    let unsubscribe = null;
    function init() {
      unsubscribe = window.autorun(() => {
        const processChildren = node => {
          if (typeof node === "string") {
            let processedNode = node;
            for (const [key, value] of window.rootStore.variableStore.values.entries()) {
              const escapedKey = key.replaceAll(/[.*+?^${}()|[\]\\]/g, (String.raw)`\$&`);
              processedNode = processedNode.replaceAll(new RegExp(escapedKey, "g"), value);
            }
            return processedNode;
          } else if (Array.isArray(node)) {
            return node.map(processChildren);
          } else if (node && node.props && node.props.children) {
            return {
              ...node,
              props: {
                ...node.props,
                children: processChildren(node.props.children)
              }
            };
          }
          return node;
        };
        setProcessedChildren(processChildren(children));
      });
    }
    if (window.rootStore) {
      init();
    } else {
      window.addEventListener("adu:storeReady", init);
    }
    return () => {
      window.removeEventListener("adu:storeReady", init);
      unsubscribe?.();
    };
  }, [children]);
  return <CodeGroup dropdown={dropdown}>{processedChildren}</CodeGroup>;
};

export const AuthCodeBlock = ({filename, icon, language, highlight, children}) => {
  const [displayText, setDisplayText] = useState(children);
  const [copyText, setCopyText] = useState(children);
  const wrapperRef = React.useRef(null);
  useEffect(() => {
    let unsubscribe = null;
    function init() {
      if (!window.autorun || !window.rootStore) {
        return;
      }
      unsubscribe = window.autorun(() => {
        let processedChildrenForDisplay = children;
        let processedChildrenForCopy = children;
        for (const [key, value] of window.rootStore.variableStore.values.entries()) {
          const escapedKey = key.replaceAll(/[.*+?^${}()|[\]\\]/g, (String.raw)`\$&`);
          let displayValue = value;
          if (key === "{yourClientSecret}" && value !== "{yourClientSecret}") {
            displayValue = value.substring(0, 3) + "*****MASKED*****";
          }
          processedChildrenForDisplay = processedChildrenForDisplay.replaceAll(new RegExp(escapedKey, "g"), displayValue);
          processedChildrenForCopy = processedChildrenForCopy.replaceAll(new RegExp(escapedKey, "g"), value);
        }
        setDisplayText(processedChildrenForDisplay);
        setCopyText(processedChildrenForCopy);
      });
    }
    if (window.rootStore) {
      init();
    } else {
      window.addEventListener("adu:storeReady", init);
    }
    return () => {
      window.removeEventListener("adu:storeReady", init);
      unsubscribe?.();
    };
  }, [children]);
  useEffect(() => {
    if (!wrapperRef.current) return;
    const originalWriteText = navigator.clipboard.writeText.bind(navigator.clipboard);
    let isOverriding = false;
    const handleClick = e => {
      const button = e.target.closest('[data-testid="copy-code-button"]');
      if (!button || !wrapperRef.current.contains(button)) return;
      isOverriding = true;
      navigator.clipboard.writeText = text => {
        if (isOverriding) {
          isOverriding = false;
          navigator.clipboard.writeText = originalWriteText;
          return originalWriteText(copyText);
        }
        return originalWriteText(text);
      };
      setTimeout(() => {
        if (isOverriding) {
          isOverriding = false;
          navigator.clipboard.writeText = originalWriteText;
        }
      }, 100);
    };
    const wrapper = wrapperRef.current;
    wrapper.addEventListener('click', handleClick, true);
    return () => {
      wrapper.removeEventListener('click', handleClick, true);
      if (navigator.clipboard.writeText !== originalWriteText) {
        navigator.clipboard.writeText = originalWriteText;
      }
    };
  }, [copyText]);
  return <div ref={wrapperRef}>
      <CodeBlock filename={filename} icon={icon} language={language} lines highlight={highlight}>
        {displayText}
      </CodeBlock>
    </div>;
};

ユーザーデータを一括してAuth0にインポートするには、[ユーザーインポートジョブ作成](/docs/ja-jp/api/management/v2#!/Jobs/post_users_imports)エンドポイントを使用します。一括インポートは、ユーザーを既存のデータベースやサービスからAuth0に移行するのに便利です。

<Warning>
  複数の移行方法（たとえば、自動移行をしてからユーザーの一括インポート）を使用しようとすると、`DUPLICATED_USER`エラーが発生することがあります。このエラーは、ユーザーがAuth0の内部ユーザーストアに存在するものの、テナントには存在しないことを示します。このエラーを修正するには、Auth0 Management APIの[接続ユーザー削除](https://auth0.com/docs/api/management/v2#!/Connections/delete_users_by_email)エンドポイントでユーザーを削除してから、インポートを再試行します。
</Warning>

## 前提条件

ユーザーインポートジョブを実行する前に、以下を行います。

* データベース接続をユーザーのインポートに構成して、少なくとも1つのアプリケーションに有効化します。
* パスワードをインポートする場合には、対応しているアルゴリズムの1つを使ってパスワードがハッシュ化されていることを確認します。ユーザーのパスワードが非対応のアルゴリズムでハッシュ化されている場合には、一括インポート後に初回のログインでユーザーがパスワードをリセットする必要があります。
* <Tooltip data-tooltip-id="react-containers-DefinitionTooltip-0" href="/docs/ja-jp/glossary?term=multifactor-authentication" tip="多要素認証（MFA）: ユーザー名とパスワードに加えて、SMS経由のコードなどの要素を使用するユーザー認証プロセス。" cta="用語集の表示">MFA</Tooltip>の登録をインポートする場合には、対応している`email`、`phone`または`totp`のタイプであることを確認します。
* ジョブエンドポイントの要求に、[Management APIトークンを取得](/docs/ja-jp/secure/tokens/access-tokens/management-api-access-tokens)します。

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  Auth0テナントからエクスポートしたファイルを使用する場合は、`ndjson`から[JSON](https://auth0.com/docs/manage-users/user-migration/bulk-user-exports#json-compatible-format)に変換する必要があります。同じユーザーIDを維持するために、インポートするユーザーIDから`auth0| prefix`を削除しなければなりません。

  インポート処理では、ユーザーIDに自動的に`auth0| prefix`が追加されます。インポートする前に`auth0| prefix`を削除しなかった場合、ユーザーIDは、`auth0|auth0|...`として返されます。
</Callout>

## ユーザーのJSONファイルを作成する

Auth0にインポートしたいユーザーデータを含むJSONファイルを作成します。ユーザーデータをJSONファイルにエクスポートする方法は、既存のユーザーデータベースによって異なります。<Tooltip data-tooltip-id="react-containers-DefinitionTooltip-0" href="/docs/ja-jp/glossary?term=management-api" tip="Management API: 顧客が管理タスクを実行できるようにするための製品。" cta="用語集の表示">Management API</Tooltip>のエンドポイントはJSONファイルを期待します。そのため、`fs.readFileSync`ではなく、`fs.createReadStream`を使用する必要があります。エンドポイントは、JSONファイルではなく、パイプで連結された読み出しストリームを期待します。

JSONファイルのスキーマと例については、「[一括インポートのデータベーススキーマと例](/docs/ja-jp/manage-users/user-migration/bulk-user-import-database-schema-and-examples)」をお読みください。

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  一括インポートでのファイルサイズは、500 KBが上限です。データがこのサイズを上回る場合には、複数のインポートを開始する必要があります。
</Callout>

## 一括ユーザーインポートを要求する

一括ユーザーインポートジョブを始めるには、`POST`要求を[一括ユーザーインポートジョブ作成](https://auth0.com/docs/api/management/v2#!/Jobs/post_users_imports)エンドポイントに対して行います。必ず、`MGMT_API_ACCESS_TOKEN`、`USERS_IMPORT_FILE.json`、`CONNECTION_ID`、および`EXTERNAL_ID`のプレースホルダーの値をそれぞれManagement APIのアクセストークン、ユーザーのJSONファイル、データベース[接続ID](/docs/ja-jp/authenticate/identity-providers/locate-the-connection-id)と外部IDに置き換えます。

<AuthCodeGroup>
  ```bash cURL theme={null}
  curl --request POST \
    --url 'https://{yourDomain}/api/v2/jobs/users-imports' \
    --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \
    --form users=@USERS_IMPORT_FILE.json \
    --form connection_id=CONNECTION_ID \
    --form external_id=EXTERNAL_ID
  ```

  ```csharp C# theme={null}
  var client = new RestClient("https://{yourDomain}/api/v2/jobs/users-imports");
  var request = new RestRequest(Method.POST);
  request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN");
  request.AddHeader("content-type", "multipart/form-data; boundary=---011000010111000001101001");
  request.AddParameter("multipart/form-data; boundary=---011000010111000001101001", "-----011000010111000001101001\r
  Content-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r
  Content-Type: text/json\r
  \r
  \r
  -----011000010111000001101001\r
  Content-Disposition: form-data; name="connection_id"\r
  \r
  CONNECTION_ID\r
  -----011000010111000001101001\r
  Content-Disposition: form-data; name="external_id"\r
  \r
  EXTERNAL_ID\r
  -----011000010111000001101001--\r
  ", ParameterType.RequestBody);
  IRestResponse response = client.Execute(request);
  ```

  ```go Go theme={null}
  package main

  import (
  	"fmt"
  	"strings"
  	"net/http"
  	"io/ioutil"
  )

  func main() {

  	url := "https://{yourDomain}/api/v2/jobs/users-imports"

  	payload := strings.NewReader("-----011000010111000001101001\r
  Content-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r
  Content-Type: text/json\r
  \r
  \r
  -----011000010111000001101001\r
  Content-Disposition: form-data; name="connection_id"\r
  \r
  CONNECTION_ID\r
  -----011000010111000001101001\r
  Content-Disposition: form-data; name="external_id"\r
  \r
  EXTERNAL_ID\r
  -----011000010111000001101001--\r
  ")

  	req, _ := http.NewRequest("POST", url, payload)

  	req.Header.Add("authorization", "Bearer MGMT_API_ACCESS_TOKEN")
  	req.Header.Add("content-type", "multipart/form-data; boundary=---011000010111000001101001")

  	res, _ := http.DefaultClient.Do(req)

  	defer res.Body.Close()
  	body, _ := ioutil.ReadAll(res.Body)

  	fmt.Println(res)
  	fmt.Println(string(body))

  }
  ```

  ```java Java theme={null}
  HttpResponse<String> response = Unirest.post("https://{yourDomain}/api/v2/jobs/users-imports")
    .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN")
    .header("content-type", "multipart/form-data; boundary=---011000010111000001101001")
    .body("-----011000010111000001101001\r
  Content-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r
  Content-Type: text/json\r
  \r
  \r
  -----011000010111000001101001\r
  Content-Disposition: form-data; name="connection_id"\r
  \r
  CONNECTION_ID\r
  -----011000010111000001101001\r
  Content-Disposition: form-data; name="external_id"\r
  \r
  EXTERNAL_ID\r
  -----011000010111000001101001--\r
  ")
    .asString();
  ```

  ```javascript Node.JS theme={null}
  var axios = require("axios").default;

  var options = {
    method: 'POST',
    url: 'https://{yourDomain}/api/v2/jobs/users-imports',
    headers: {
      authorization: 'Bearer MGMT_API_ACCESS_TOKEN',
      'content-type': 'multipart/form-data; boundary=---011000010111000001101001'
    },
    data: '-----011000010111000001101001\r
  Content-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r
  Content-Type: text/json\r
  \r
  \r
  -----011000010111000001101001\r
  Content-Disposition: form-data; name="connection_id"\r
  \r
  CONNECTION_ID\r
  -----011000010111000001101001\r
  Content-Disposition: form-data; name="external_id"\r
  \r
  EXTERNAL_ID\r
  -----011000010111000001101001--\r
  '
  };

  axios.request(options).then(function (response) {
    console.log(response.data);
  }).catch(function (error) {
    console.error(error);
  });
  ```

  ```objc Obj-C theme={null}
  #import <Foundation/Foundation.h>

  NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN",
                             @"content-type": @"multipart/form-data; boundary=---011000010111000001101001" };
  NSArray *parameters = @[ @{ @"name": @"users", @"fileName": @"USERS_IMPORT_FILE.json", @"contentType": @"text/json" },
                           @{ @"name": @"connection_id", @"value": @"CONNECTION_ID" },
                           @{ @"name": @"external_id", @"value": @"EXTERNAL_ID" } ];
  NSString *boundary = @"---011000010111000001101001";

  NSError *error;
  NSMutableString *body = [NSMutableString string];
  for (NSDictionary *param in parameters) {
      [body appendFormat:@"--%@\r
  ", boundary];
      if (param[@"fileName"]) {
          [body appendFormat:@"Content-Disposition:form-data; name="%@"; filename="%@"\r
  ", param[@"name"], param[@"fileName"]];
          [body appendFormat:@"Content-Type: %@\r
  \r
  ", param[@"contentType"]];
          [body appendFormat:@"%@", [NSString stringWithContentsOfFile:param[@"fileName"] encoding:NSUTF8StringEncoding error:&error]];
          if (error) {
              NSLog(@"%@", error);
          }
      } else {
          [body appendFormat:@"Content-Disposition:form-data; name="%@"\r
  \r
  ", param[@"name"]];
          [body appendFormat:@"%@", param[@"value"]];
      }
  }
  [body appendFormat:@"\r
  --%@--\r
  ", boundary];
  NSData *postData = [body dataUsingEncoding:NSUTF8StringEncoding];

  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{yourDomain}/api/v2/jobs/users-imports"]
                                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                     timeoutInterval:10.0];
  [request setHTTPMethod:@"POST"];
  [request setAllHTTPHeaderFields:headers];
  [request setHTTPBody:postData];

  NSURLSession *session = [NSURLSession sharedSession];
  NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                              completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                  if (error) {
                                                      NSLog(@"%@", error);
                                                  } else {
                                                      NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                                      NSLog(@"%@", httpResponse);
                                                  }
                                              }];
  [dataTask resume];
  ```

  ```php PHP theme={null}
  $curl = curl_init();

  curl_setopt_array($curl, [
    CURLOPT_URL => "https://{yourDomain}/api/v2/jobs/users-imports",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => "-----011000010111000001101001\r
  Content-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r
  Content-Type: text/json\r
  \r
  \r
  -----011000010111000001101001\r
  Content-Disposition: form-data; name="connection_id"\r
  \r
  CONNECTION_ID\r
  -----011000010111000001101001\r
  Content-Disposition: form-data; name="external_id"\r
  \r
  EXTERNAL_ID\r
  -----011000010111000001101001--\r
  ",
    CURLOPT_HTTPHEADER => [
      "authorization: Bearer MGMT_API_ACCESS_TOKEN",
      "content-type: multipart/form-data; boundary=---011000010111000001101001"
    ],
  ]);

  $response = curl_exec($curl);
  $err = curl_error($curl);

  curl_close($curl);

  if ($err) {
    echo "cURL Error #:" . $err;
  } else {
    echo $response;
  }
  ```

  ```python Python theme={null}
  import http.client

  conn = http.client.HTTPSConnection("")

  payload = "-----011000010111000001101001\r
  Content-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r
  Content-Type: text/json\r
  \r
  \r
  -----011000010111000001101001\r
  Content-Disposition: form-data; name="connection_id"\r
  \r
  CONNECTION_ID\r
  -----011000010111000001101001\r
  Content-Disposition: form-data; name="external_id"\r
  \r
  EXTERNAL_ID\r
  -----011000010111000001101001--\r
  "

  headers = {
      'authorization': "Bearer MGMT_API_ACCESS_TOKEN",
      'content-type': "multipart/form-data; boundary=---011000010111000001101001"
      }

  conn.request("POST", "/{yourDomain}/api/v2/jobs/users-imports", payload, headers)

  res = conn.getresponse()
  data = res.read()

  print(data.decode("utf-8"))
  ```

  ```ruby Ruby theme={null}
  require 'uri'
  require 'net/http'
  require 'openssl'

  url = URI("https://{yourDomain}/api/v2/jobs/users-imports")

  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE

  request = Net::HTTP::Post.new(url)
  request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN'
  request["content-type"] = 'multipart/form-data; boundary=---011000010111000001101001'
  request.body = "-----011000010111000001101001\r
  Content-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r
  Content-Type: text/json\r
  \r
  \r
  -----011000010111000001101001\r
  Content-Disposition: form-data; name="connection_id"\r
  \r
  CONNECTION_ID\r
  -----011000010111000001101001\r
  Content-Disposition: form-data; name="external_id"\r
  \r
  EXTERNAL_ID\r
  -----011000010111000001101001--\r
  "

  response = http.request(request)
  puts response.read_body
  ```

  ```swift Swift theme={null}
  import Foundation

  let headers = [
    "authorization": "Bearer MGMT_API_ACCESS_TOKEN",
    "content-type": "multipart/form-data; boundary=---011000010111000001101001"
  ]
  let parameters = [
    [
      "name": "users",
      "fileName": "USERS_IMPORT_FILE.json",
      "contentType": "text/json"
    ],
    [
      "name": "connection_id",
      "value": "CONNECTION_ID"
    ],
    [
      "name": "external_id",
      "value": "EXTERNAL_ID"
    ]
  ]

  let boundary = "---011000010111000001101001"

  var body = ""
  var error: NSError? = nil
  for param in parameters {
    let paramName = param["name"]!
    body += "--\(boundary)\r
  "
    body += "Content-Disposition:form-data; name="\(paramName)""
    if let filename = param["fileName"] {
      let contentType = param["content-type"]!
      let fileContent = String(contentsOfFile: filename, encoding: String.Encoding.utf8)
      if (error != nil) {
        print(error)
      }
      body += "; filename="\(filename)"\r
  "
      body += "Content-Type: \(contentType)\r
  \r
  "
      body += fileContent
    } else if let paramValue = param["value"] {
      body += "\r
  \r
  \(paramValue)"
    }
  }

  let request = NSMutableURLRequest(url: NSURL(string: "https://{yourDomain}/api/v2/jobs/users-imports")! as URL,
                                          cachePolicy: .useProtocolCachePolicy,
                                      timeoutInterval: 10.0)
  request.httpMethod = "POST"
  request.allHTTPHeaderFields = headers
  request.httpBody = postData as Data

  let session = URLSession.shared
  let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
    if (error != nil) {
      print(error)
    } else {
      let httpResponse = response as? HTTPURLResponse
      print(httpResponse)
    }
  })

  dataTask.resume()
  ```
</AuthCodeGroup>

| パラメーター                  | 説明                                                                                                                                                                                                                                                                                                                                                                           |
| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `users`                 | インポートするユーザーを含むJSON形式のファイルです。                                                                                                                                                                                                                                                                                                                                                 |
| `connection_id`         | ユーザーが投入される接続のIDです。IDは[GET /api/v2/connections](https://auth0.com/docs/ja-jp/api/management/v2#!/Connections/get_connections)を使って取得することができます。                                                                                                                                                                                                                                 |
| `upsert`                | ブール値で、デフォルトは`false`です。`false`では、メールアドレス、ユーザーID、電話番号、またはユーザー名が一致する既存のユーザーの場合、エラーになります。trueでは、メールアドレスが一致する既存のユーザーは更新されますが、更新されるのはアップサートできる属性のみです。インポートでアップサート可能なユーザープロファイルのフィールドについては、「[ユーザープロファイルの構造：ユーザープロファイル属性](https://auth0.com/docs/ja-jp/users/user-profile-structure#user-profile-attributes)」を参照してください。注意：インポートファイルに重複したユーザーが存在する場合はエラーになります。その場合、Auth0は投入や更新を行いません。 |
| `external_id`           | 任意のユーザー定義の文字列で、複数のジョブを関連付けるのに使うことができます。ジョブステータス応答の一部として返されます。                                                                                                                                                                                                                                                                                                                |
| `send_completion_email` | ブール値で、デフォルトは`true`です。`true`では、インポートジョブが終了すると、すべてのテナント所有者に完了メールを送信します。メールを送信したく*ない*場合には、このパラメーターを`false`に設定する必要があります。                                                                                                                                                                                                                                                         |

要求に成功すると、以下のような応答を受け取ります。

```json lines theme={null}
{
  "status": "pending",
  "type": "users_import",
  "created_at": "",
  "id": "job_abc123",
  "connection_id": "CONNECTION_ID",
  "upsert": false,
  "external_id": "EXTERNAL_ID",
  "send_completion_email": true
}
```

返されたエンティティはインポートジョブを表します。

ユーザーインポートジョブが完了すると、`send_completion_email`が`true`に設定されている場合には、ジョブの成功または失敗がテナント管理者に通知されます。ジョブ失敗のメールでは、ユーザーのインポートでユーザーのJSONファイルが解析に失敗したことを管理者に知らせる場合もあります。

### 複数のインポートジョブを同時に実行する

[ユーザーインポートジョブ作成](https://auth0.com/docs/api/management/v2#!/Jobs/post_users_imports)エンドポイントでは、同時に実行可能なインポートジョブが2つまでに制限されています。2つのジョブが保留中の場合に追加のジョブを要求すると、`429 Too Many Requests`（要求が多すぎます）応答が返されます。

```json lines theme={null}
{
  "statusCode": 429,
  "error": "Too Many Requests",
  "message": "There are 2 active import users jobs, please wait until some of them are finished and try again
}
```

## ジョブステータスを確認する

ジョブのステータスを確認するには、`GET`要求を[ジョブ取得](https://auth0.com/docs/api/management/v2#!/Jobs/get_jobs_by_id)エンドポイントに対して行います。必ず、`MGMT_API_ACCESS_TOKEN`および`JOB_ID`のプレースホルダーの値をそれぞれManagement APIのアクセストークンとユーザーインポートジョブIDに置き換えます。

<AuthCodeGroup>
  ```bash cURL theme={null}
  curl --request GET \
    --url 'https://{yourDomain}/api/v2/jobs/JOB_ID' \
    --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \
    --header 'content-type: application/json'
  ```

  ```csharp C# theme={null}
  var client = new RestClient("https://{yourDomain}/api/v2/jobs/JOB_ID");
  var request = new RestRequest(Method.GET);
  request.AddHeader("content-type", "application/json");
  request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN");
  IRestResponse response = client.Execute(request);
  ```

  ```go Go theme={null}
  package main

  import (
  	"fmt"
  	"net/http"
  	"io/ioutil"
  )

  func main() {

  	url := "https://{yourDomain}/api/v2/jobs/JOB_ID"

  	req, _ := http.NewRequest("GET", url, nil)

  	req.Header.Add("content-type", "application/json")
  	req.Header.Add("authorization", "Bearer MGMT_API_ACCESS_TOKEN")

  	res, _ := http.DefaultClient.Do(req)

  	defer res.Body.Close()
  	body, _ := ioutil.ReadAll(res.Body)

  	fmt.Println(res)
  	fmt.Println(string(body))

  }
  ```

  ```java Java theme={null}
  HttpResponse<String> response = Unirest.get("https://{yourDomain}/api/v2/jobs/JOB_ID")
    .header("content-type", "application/json")
    .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN")
    .asString();
  ```

  ```javascript Node.JS theme={null}
  var axios = require("axios").default;

  var options = {
    method: 'GET',
    url: 'https://{yourDomain}/api/v2/jobs/JOB_ID',
    headers: {
      'content-type': 'application/json',
      authorization: 'Bearer MGMT_API_ACCESS_TOKEN'
    }
  };

  axios.request(options).then(function (response) {
    console.log(response.data);
  }).catch(function (error) {
    console.error(error);
  });
  ```

  ```objc Obj-C theme={null}
  #import <Foundation/Foundation.h>

  NSDictionary *headers = @{ @"content-type": @"application/json",
                             @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" };

  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{yourDomain}/api/v2/jobs/JOB_ID"]
                                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                     timeoutInterval:10.0];
  [request setHTTPMethod:@"GET"];
  [request setAllHTTPHeaderFields:headers];

  NSURLSession *session = [NSURLSession sharedSession];
  NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                              completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                  if (error) {
                                                      NSLog(@"%@", error);
                                                  } else {
                                                      NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                                      NSLog(@"%@", httpResponse);
                                                  }
                                              }];
  [dataTask resume];
  ```

  ```php PHP theme={null}
  $curl = curl_init();

  curl_setopt_array($curl, [
    CURLOPT_URL => "https://{yourDomain}/api/v2/jobs/JOB_ID",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => [
      "authorization: Bearer MGMT_API_ACCESS_TOKEN",
      "content-type: application/json"
    ],
  ]);

  $response = curl_exec($curl);
  $err = curl_error($curl);

  curl_close($curl);

  if ($err) {
    echo "cURL Error #:" . $err;
  } else {
    echo $response;
  }
  ```

  ```python Python theme={null}
  import http.client

  conn = http.client.HTTPSConnection("")

  headers = {
      'content-type': "application/json",
      'authorization': "Bearer MGMT_API_ACCESS_TOKEN"
      }

  conn.request("GET", "/{yourDomain}/api/v2/jobs/JOB_ID", headers=headers)

  res = conn.getresponse()
  data = res.read()

  print(data.decode("utf-8"))
  ```

  ```ruby Ruby theme={null}
  require 'uri'
  require 'net/http'
  require 'openssl'

  url = URI("https://{yourDomain}/api/v2/jobs/JOB_ID")

  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE

  request = Net::HTTP::Get.new(url)
  request["content-type"] = 'application/json'
  request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN'

  response = http.request(request)
  puts response.read_body
  ```

  ```swift Swift theme={null}
  import Foundation

  let headers = [
    "content-type": "application/json",
    "authorization": "Bearer MGMT_API_ACCESS_TOKEN"
  ]

  let request = NSMutableURLRequest(url: NSURL(string: "https://{yourDomain}/api/v2/jobs/JOB_ID")! as URL,
                                          cachePolicy: .useProtocolCachePolicy,
                                      timeoutInterval: 10.0)
  request.httpMethod = "GET"
  request.allHTTPHeaderFields = headers

  let session = URLSession.shared
  let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
    if (error != nil) {
      print(error)
    } else {
      let httpResponse = response as? HTTPURLResponse
      print(httpResponse)
    }
  })

  dataTask.resume()
  ```
</AuthCodeGroup>

ユーザーインポートジョブのステータスに応じて、以下のような応答の1つを受け取ります。

**保留中**

```javascript lines theme={null}
{
  "status": "pending",
  "type": "users_import",
  "created_at": "",
  "id": "job_abc123",
  "connection_id": "CONNECTION_ID",
  "external_id": "EXTERNAL_ID"
}
```

**完了**

ジョブが完了すると、ジョブステータス応答には、成功、失敗、挿入、および更新レコードの総計が含めれます。

```javascript lines theme={null}
{
  "status": "completed",
  "type": "users_import",
  "created_at": "",
  "id": "job_abc123",
  "connection_id": "CONNECTION_ID",
  "external_id": "EXTERNAL_ID",
  "summary": {
    "failed": 0,
    "updated": 0,
    "inserted": 1,
    "total": 1
  }
}
```

**失敗**

ジョブ内にエラーがある場合には、失敗が返されます。ただし、無効なメールなどの無効なユーザー情報では、ジョブが全体として失敗しないことに注意してください。

```javascript lines theme={null}
{
  "status": "failed",
  "type": "users_import",
  "created_at": "",
  "id": "job_abc123",
  "connection_id": "CONNECTION_ID",
  "external_id": "EXTERNAL_ID",
}
```

失敗エントリの詳細については、以下で「**失敗エントリを取得する** 」を参照してください。

## ジョブのタイムアウト

すべてのユーザーインポートジョブは、**2時間** が経過するとタイムアウトします。ジョブがこの時間制限内に完了しない場合は、失敗としてマークされます。

また、ジョブ関連のデータはすべて24時間後に自動削除され、アクセスできなくなります。そのため、**何らかのストレージメカニズムを使ってジョブ結果を保管することを強くお勧めします** 。

## ログエントリを取得する

<Warning>
  ジョブ関連のデータは、すべて24時間後に自動削除され、アクセスできなくなります。そのため、何らかの保管メカニズムを使ってジョブ結果を保管することを強くお勧めします。
</Warning>

ユーザーインポートジョブにエラーがある場合には、`GET`要求を[ジョブエラー詳細取得](/docs/ja-jp/api/management/v2#!/Jobs/get_errors)エンドポイントに行って、エラー詳細を取得することができます。必ず、`MGMT_API_ACCESS_TOKEN`および`JOB_ID`のプレースホルダーの値をそれぞれManagement APIのアクセストークンとユーザーインポートジョブIDに置き換えます。

<AuthCodeGroup>
  ```bash cURL theme={null}
  curl --request GET \
    --url 'https://{yourDomain}/api/v2/jobs/JOB_ID/errors' \
    --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \
    --header 'content-type: application/json'
  ```

  ```csharp C# theme={null}
  var client = new RestClient("https://{yourDomain}/api/v2/jobs/JOB_ID/errors");
  var request = new RestRequest(Method.GET);
  request.AddHeader("content-type", "application/json");
  request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN");
  IRestResponse response = client.Execute(request);
  ```

  ```go Go theme={null}
  package main

  import (
  	"fmt"
  	"net/http"
  	"io/ioutil"
  )

  func main() {

  	url := "https://{yourDomain}/api/v2/jobs/JOB_ID/errors"

  	req, _ := http.NewRequest("GET", url, nil)

  	req.Header.Add("content-type", "application/json")
  	req.Header.Add("authorization", "Bearer MGMT_API_ACCESS_TOKEN")

  	res, _ := http.DefaultClient.Do(req)

  	defer res.Body.Close()
  	body, _ := ioutil.ReadAll(res.Body)

  	fmt.Println(res)
  	fmt.Println(string(body))

  }
  ```

  ```java Java theme={null}
  HttpResponse<String> response = Unirest.get("https://{yourDomain}/api/v2/jobs/JOB_ID/errors")
    .header("content-type", "application/json")
    .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN")
    .asString();
  ```

  ```javascript Node.JS theme={null}
  var axios = require("axios").default;

  var options = {
    method: 'GET',
    url: 'https://{yourDomain}/api/v2/jobs/JOB_ID/errors',
    headers: {
      'content-type': 'application/json',
      authorization: 'Bearer MGMT_API_ACCESS_TOKEN'
    }
  };

  axios.request(options).then(function (response) {
    console.log(response.data);
  }).catch(function (error) {
    console.error(error);
  });
  ```

  ```objc Obj-C theme={null}
  #import <Foundation/Foundation.h>

  NSDictionary *headers = @{ @"content-type": @"application/json",
                             @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" };

  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{yourDomain}/api/v2/jobs/JOB_ID/errors"]
                                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                     timeoutInterval:10.0];
  [request setHTTPMethod:@"GET"];
  [request setAllHTTPHeaderFields:headers];

  NSURLSession *session = [NSURLSession sharedSession];
  NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                              completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                  if (error) {
                                                      NSLog(@"%@", error);
                                                  } else {
                                                      NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                                      NSLog(@"%@", httpResponse);
                                                  }
                                              }];
  [dataTask resume];
  ```

  ```php PHP theme={null}
  $curl = curl_init();

  curl_setopt_array($curl, [
    CURLOPT_URL => "https://{yourDomain}/api/v2/jobs/JOB_ID/errors",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => [
      "authorization: Bearer MGMT_API_ACCESS_TOKEN",
      "content-type: application/json"
    ],
  ]);

  $response = curl_exec($curl);
  $err = curl_error($curl);

  curl_close($curl);

  if ($err) {
    echo "cURL Error #:" . $err;
  } else {
    echo $response;
  }
  ```

  ```python Python theme={null}
  import http.client

  conn = http.client.HTTPSConnection("")

  headers = {
      'content-type': "application/json",
      'authorization': "Bearer MGMT_API_ACCESS_TOKEN"
      }

  conn.request("GET", "/{yourDomain}/api/v2/jobs/JOB_ID/errors", headers=headers)

  res = conn.getresponse()
  data = res.read()

  print(data.decode("utf-8"))
  ```

  ```ruby Ruby theme={null}
  require 'uri'
  require 'net/http'
  require 'openssl'

  url = URI("https://{yourDomain}/api/v2/jobs/JOB_ID/errors")

  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE

  request = Net::HTTP::Get.new(url)
  request["content-type"] = 'application/json'
  request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN'

  response = http.request(request)
  puts response.read_body
  ```

  ```swift Swift theme={null}
  import Foundation

  let headers = [
    "content-type": "application/json",
    "authorization": "Bearer MGMT_API_ACCESS_TOKEN"
  ]

  let request = NSMutableURLRequest(url: NSURL(string: "https://{yourDomain}/api/v2/jobs/JOB_ID/errors")! as URL,
                                          cachePolicy: .useProtocolCachePolicy,
                                      timeoutInterval: 10.0)
  request.httpMethod = "GET"
  request.allHTTPHeaderFields = headers

  let session = URLSession.shared
  let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
    if (error != nil) {
      print(error)
    } else {
      let httpResponse = response as? HTTPURLResponse
      print(httpResponse)
    }
  })

  dataTask.resume()
  ```
</AuthCodeGroup>

要求に成功すると、以下のような応答を受け取ります。`hash.value`などの機密フィールドは応答内でマスクされます。

```json lines theme={null}
[
    {
        "user": {
            "email": "test@test.io",
            "user_id": "7af4c65cb0ac6e162f081822422a9dde",
            "custom_password_hash": {
                "algorithm": "ldap",
                "hash": {
                    "value": "*****"
                }
            }
        },
        "errors": [
            {
                "code": "...",
                "message": "...",
                "path": "..."
            }
        ]
    }
]
```

それぞれのエラーオブジェクトには、エラーコードとエラー詳細を説明するメッセージが含まれます。以下のようなエラーコードがあります。

* ANY\_OF\_MISSING
* ARRAY\_LENGTH\_LONG
* ARRAY\_LENGTH\_SHORT
* CONFLICT
* CONFLICT\_EMAIL
* CONFLICT\_USERNAME
* CONNECTION\_NOT\_FOUND
* DUPLICATED\_USER
* ENUM\_MISMATCH
* FORMAT
* INVALID\_TYPE
* MAX\_LENGTH
* MAXIMUM
* MFA\_FACTORS\_FAILED
* MIN\_LENGTH
* MINIMUM
* NOT\_PASSED
* OBJECT\_REQUIRED
* PATTERN

## もっと詳しく

* [データベースからの自動移行を構成する](/docs/ja-jp/manage-users/user-migration/configure-automatic-migration-from-your-database)
* [ユーザーのインポート/エクスポート拡張機能](/docs/ja-jp/manage-users/user-migration/user-import-export-extension)
* [一括ユーザーインポートのデータベーススキーマと例](/docs/ja-jp/manage-users/user-migration/bulk-user-import-database-schema-and-examples)
* [ユーザー移行のシナリオ](/docs/ja-jp/manage-users/user-migration/user-migration-scenarios)
