Введение. Разработка приложений с использованием API переносимости данных.
Оптимизируйте свои подборки
Сохраняйте и классифицируйте контент в соответствии со своими настройками.
API переносимости данных позволяет создавать приложения, которые запрашивают у пользователя разрешение на перемещение копии данных из сервисов Google в ваше приложение. Это обеспечивает переносимость данных и облегчает переключение услуг.
Прежде чем выпускать ваше приложение, оно должно быть одобрено Google.
Вам также следует убедиться, что API переносимости данных доступен пользователям в вашем регионе. Список поддерживаемых стран и регионов см. в разделе «Общие вопросы» на странице «Отправка копии своих данных третьему лицу».
Рабочий процесс разработчика
Ниже приведены шаги, которые необходимо выполнить для создания приложения, использующего API переносимости данных.
Реализуйте поток согласия OAuth для пользователя. В этом примере пользователь предоставляет доступ к видеоданным YouTube.
Пользователь нажимает «Импортировать видео с YouTube» и входит в свою учетную запись Google.
Приложение перенаправляет пользователя на URL-адрес согласия OAuth. Обратите внимание, что этот пример URL-адреса упрощен и в нем отсутствуют некоторые параметры:
Пользователь нажимает «Далее» на экране согласия OAuth, соглашается поделиться своими данными и предоставляет доступ к учетной записи.
Пользователь выбирает, какими данными делиться, а также время, в течение которого приложение может получать доступ к этим данным ( однократный доступ к своим данным или доступ по времени в течение 30 или 180 дней), а затем нажимает «Продолжить» .
Примечание . За 90 дней до истечения срока действия вашего токена OAuth пользователь имеет возможность продлить доступ к своим данным до истечения срока действия вашего токена OAuth. Кнопка продления не отображается, если у пользователя нет областей действия, срок действия которых истекает в течение 90 дней.
Примечание . Если пользователь хочет переключиться между однократным доступом и доступом на основе времени, ему придется снова пройти процедуру согласия после отзыва существующего разрешения. Вы можете отозвать грант с помощью resetAuthorization() , или пользователь может отозвать его на странице своих подключений .
Пользователь перенаправляется в приложение.
Разработчик получает токен OAuth для пользователя.
Ваше приложение вызывает InitiatePortabilityArchive(resources = ["myactivity.youtube"]) с прикрепленным токеном OAuth, который содержит эту область OAuth:
Этот вызов запускает процесс создания архива данных и отвечает идентификатором задания и указанием того, предоставил ли пользователь однократный или временной доступ.
Примечание . Одноразовый доступ означает один экспорт для каждой области . Если пользователь предоставляет несколько областей, вы можете создать отдельные задания для каждого ресурса, авторизованного токеном.
Ваше приложение вызывает GetPortabilityArchiveState(job_id) с прикрепленным токеном OAuth, который содержит эту область OAuth:
Вы можете вызвать этот метод несколько раз, чтобы получить статус задания архивирования. Метод возвращает состояние задания. Если состояние COMPLETE , архив готов и предоставлены подписанные URL-адреса облачного хранилища. Обратите внимание, что время, необходимое для выполнения запроса на архивирование, может варьироваться от минут до часов в зависимости от размера данных.
Загрузите архив данных, используя подписанные URL-адреса.
Если пользователь предоставляет однократный доступ , вы вызываете ResetAuthorization() с прикрепленным токеном OAuth, чтобы сбросить исчерпанные ресурсы и удалить все разрешения OAuth.
Если пользователь предоставляет доступ на основе времени , вы можете экспортировать ресурсы каждые 24 часа, пока не истечет срок действия согласия.
Как пользователи взаимодействуют с приложением API переносимости данных
На этой диаграмме показано, как пользователи взаимодействуют с приложением, интегрированным с API переносимости данных.
Во-первых, пользователю предоставляется возможность получить свои данные.
Затем пользователь входит в свою учетную запись Google.
Затем пользователь нажимает «Далее» , когда ему предлагается поделиться своими данными, и нажимает «Я понимаю» , когда ему предлагается принять политику конфиденциальности.
Затем пользователю отображается экран согласия OAuth, который позволяет приложению получить доступ к его данным. Указанные здесь параметры соответствуют настроенным вами областям OAuth. Пользователь выбирает, какими данными делиться и в течение какого времени приложение может получать доступ к этим данным ( однократный доступ к своим данным или доступ по времени в течение 30 или 180 дней), а затем нажимает «Продолжить» .
После разрешения доступа начнется импорт данных. В зависимости от размера данных выполнение запроса может занять от нескольких минут до нескольких часов.
[null,null,["Последнее обновление: 2025-07-24 UTC."],[[["\u003cp\u003eThe Data Portability API allows developers to build applications that enable users to move a copy of their data from Google services to another application, facilitating service switching.\u003c/p\u003e\n"],["\u003cp\u003eBefore releasing an application using this API, developers must obtain approval from Google and ensure the API is available in the user's region.\u003c/p\u003e\n"],["\u003cp\u003eThe developer workflow involves implementing the OAuth consent flow, initiating the data archive creation, monitoring its status, downloading the archive using provided URLs, and finally resetting authorization.\u003c/p\u003e\n"],["\u003cp\u003eUsers interact with Data Portability API applications by initiating data retrieval, signing into their Google Account, granting necessary permissions, and waiting for the data import process to complete.\u003c/p\u003e\n"],["\u003cp\u003eData Portability API features are not accessible to users under 18 years of age, resulting in an error message if they attempt to use them.\u003c/p\u003e\n"]]],[],null,["# Introduction: Develop apps using the Data Portability API\n\nThe Data Portability API lets you build applications that request authorization from a\nuser to move a copy of data from Google services into your application. This\nenables data portability and facilitates switching services.\n\nIf you are looking for information on how users share data, see [Share a copy of\nyour data with a third party](https://support.google.com/accounts/answer/14452558).\n\nPrerequisites\n-------------\n\nBefore releasing your app, it must be [approved](/data-portability/user-guide/client-verification) by Google.\n\nYou should also verify that the Data Portability API is available to users in\nyour location. For a list of supported countries and regions, see\n[Common Questions](https://support.google.com/accounts/answer/14452558) on the \"Share a copy of your data with a third\nparty\" page.\n\nDeveloper workflow\n------------------\n\nThese are the steps you follow to create an application that uses the\nData Portability API.\n\n1. Implement the OAuth consent flow for the user. In this example, the user is\n providing access to YouTube video data.\n\n 1. The user clicks **Import YouTube Videos** and signs into their Google\n Account.\n\n 2. The app forwards the user to an OAuth consent URL. Note that this\n example URL is simplified and is missing some parameters:\n\n `https://accounts.google.com/o/oauth2/v2/auth?scope=https://www.googleapis.com/auth/dataportability.myactivity.youtube`\n 3. The user clicks **Next** on the OAuth consent screen, agrees to share\n their data, and provides account access.\n\n 4. The user selects what data to share and the amount of time the app can\n access that data (*one-time access* to their data or *time-based access* for\n 30 or 180 days), then clicks **Continue**.\n\n **Note**:\n Up to 90 days before your OAuth token expires, the user has the option\n of renewing your access to their data before your OAuth token expires.\n The renew button doesn't appear if the user doesn't have scopes expiring\n within 90 days.\n\n **Note** : If the user wants to switch between *one-time access* and\n *time-based access* they will need to go through the consent flow again\n after the existing grant has been revoked. You can revoke the grant with\n `resetAuthorization()`, or the user can revoke on their [connections\n page](http://myaccount.google.com/connections).\n 5. The user is redirected to the app.\n\n 6. The developer obtains an OAuth token for the user.\n\n2. Your app calls\n `InitiatePortabilityArchive(resources = [\"myactivity.youtube\"])` with\n an attached OAuth token that contains this OAuth scope:\n\n `https://www.googleapis.com/auth/dataportability.myactivity.youtube`\n\n This call starts the process of creating the data archive and responds with\n a job ID and whether the user granted one-time or time-based access.\n\n **Note** :\n One-time access means one export *per scope*. If the user grants\n multiple scopes, you may choose to create separate jobs for each of the\n resources authorized by the token.\n | **Tip:** You should initiate the portability archive within 24 hours of user authorization.\n3. Your app calls `GetPortabilityArchiveState(job_id)` with an attached OAuth\n token that contains this OAuth scope:\n\n `https://www.googleapis.com/auth/dataportability.myactivity.youtube`\n\n You can call this method multiple times to retrieve the status of the\n archive job. The method returns the job's state. If the state is `COMPLETE`,\n the archive is ready, and signed Cloud Storage URLs are provided. Note that\n the time it takes to complete the archive request can vary from minutes to\n hours depending on the size of the data.\n4. Download the data archive using the signed URLs.\n\n5. *If the user grants one-time access* , you call `ResetAuthorization()` with\n an attached OAuth token to reset exhausted resources and to remove all OAuth\n consents.\n\n6. *If the user grants time-based access*, you can export resources every 24\n hours until the consent expires.\n\nFor more information on using the Data Portability API methods, see\n[Call Data Portability API methods](/data-portability/user-guide/methods).\n\nHow users interact with a Data Portability API app\n--------------------------------------------------\n\nThis diagram shows how users interact with an app that's integrated with the\nData Portability API.\n\n1. First, the user is presented with an option to retrieve their data.\n\n2. Next, the user signs into their Google Account.\n\n3. Then, the user clicks **Next** when they're prompted to share their data,\n and they click **I understand** when they're prompted to accept the privacy\n policy.\n\n4. Then, the user is shown an OAuth consent screen that is used to allow the\n application to access their data. The options here match the OAuth scopes\n you configured. The user selects what data to share and the amount of time\n the app can access that data (*one-time access* to their data or\n *time-based access* for 30 or 180 days), then clicks **Continue**.\n\n5. After allowing access, the data import starts. Depending on the size of the\n data, the request can take several minutes to several hours to complete."]]