azure-devopsazure-devops-rest-api

Azure DevOps API Import Repository (Status 400)


Am trying to import from 1 Repository into another within the same Project

Getting Status 400

In the code below:

In some examples online I see 'endpoint' and/or credentials being specified, but presume not required here as is within the same Project and I have admin permissions on both.

url:

https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repository_id}/importRequests?api-version=7.1

payload:

{
    "parameters": {
        "gitSource": {
            "url": "https://{organization}.visualstudio.com/xxxxxxx%20xxxxxxx%20xxxxx/_git/test%20template"
        }
    }
}

Solution

  • When calling the Azure DevOps REST API "Import Requests - Create", you must provide a Git endpoint (Other Git service connection) which can connect to the source git repository, even if the target repository and source repository are in the same project.

    If you do not provide the Git endpoint, you will get the 400 Bad Request error.

    Below is a sample with the detailed steps to call this REST API:

    1. Create a PAT (Personal Access Token) with the scope "Code (Read, write, &manage)".

      enter image description here

    2. Go the "Project Settings" > "Service connections" to create a new Other Git service connection.

      • Git repository URL: The clone URL of the source git repository.
      • Password/Token: A PAT which has the scope "Code (Read)" at least so that it can read the source git repository.
      • Service connection name: A custom name of the service connection.

      After creating the service connection, open it, you can see the value of resourceId from the URL. It will be passed as the value of serviceEndpointId in the request body of the REST API.

      enter image description here

    3. After above configuration, you can call the REST API like as below.

      • The request URI. The {organization}, {project} and {repository} should point to the target git repository.

        POST https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repository}/importRequests?api-version=7.1
        
      • The request headers should contain "Content-Type = application/json". Also use the PAT created above as the authorization token of the API call.

        enter image description here

      • The request body should contain the ID of the Git endpoint. If you want the Git endpoint to be automatically deleted after the import task gets done, you can set the 'deleteServiceEndpointAfterImportIsDone' to 'true'.

        {
          "parameters": {
            "deleteServiceEndpointAfterImportIsDone": true,
            "serviceEndpointId": "xxxx",
            "gitSource": {
              "url": "{URL of the Source Git Repo}"
            }
          }
        }
        
      • The result: 201 Created.

        enter image description here