Shashank
Shashank

Reputation: 13

Error 400: "Bad Request" When Importing GitLab Repository into Azure DevOps via REST API

I am trying to import a GitLab repository into Azure DevOps using the REST API. However, I am encountering a 400 Bad Request error during the process. Below is the core part of the code:

python code:

payload = {
"authorization":{"scheme":"UsernamePassword","parameters":{"username":"{User name}","password":"{github access token }"}},
"data":{"accessExternalGitServer":"true"},
"name":"{name}",
"serviceEndpointProjectReferences":[{"description":"","name":"{Service connection name}","projectReference":{"id":"{Project Id}","name":"{Project Name}"}}],
"type":"git",
"url":"{Target Git URL}",
"isShared":false,
"owner":"library"

}

    service_endpoint_url = f"https://dev.azure.com/{ORGANIZATION_NAME}/{project_name}/_apis/serviceendpoint/endpoints?api-version=6.0-preview.4"

    headers = {"Content-Type": "application/json"}

    response = requests.post(
        service_endpoint_url,
        auth=HTTPBasicAuth("", PERSONAL_ACCESS_TOKEN),
        headers=headers,
        data=json.dumps(payload),
        verify=False,
    )

connection_id = response.json()["id"]

# Prepare import request
import_url = f"https://dev.azure.com/{ORG_NAME}/{PROJECT}/_apis/git/repositories/{REPO_NAME}/importRequests?api-version=7.1-preview.1"

import_payload = {
    "parameters": {
        "gitSource": {
            "url": GITLAB_REPO_URL,
            "overwrite": False,
        
        },
        "serviceEndpointId": connection_id,
        "deleteServiceEndpointAfterImportIsDone": True
    }
}

headers = {
    "Content-Type": "application/json"
}

# Perform repository import
import_response = requests.post(
    import_url,
    auth=HTTPBasicAuth("", AZURE_DEVOPS_PAT),  # Placeholder for Azure DevOps PAT
    headers=headers,
    data=json.dumps(import_payload),
    verify=False
)

Error:

400 Client Error: Bad Request for url: https://dev.azure.com//<project_name>/_apis/git/repositories/<repo_name>/importRequests?api-version=7.1-preview.1

Things I've Tried:

The GitLab repository URL (GITLAB_REPO_URL) is correct and publicly accessible. The Azure DevOps Personal Access Token (AZURE_DEVOPS_PAT) has full permissions for repository imports and related operations. The repository name (ADO_REPO_NAME) and project name (PROJECT_NAME) exist and are accessible in Azure DevOps. The GITLAB_REPO_URL is in the format: https://gitlab.example.com//.git. I am using the appropriate API version (7.1-preview.1) as per Microsoft's documentation. Added service connection

Upvotes: 0

Views: 114

Answers (1)

Suresh Chikkam
Suresh Chikkam

Reputation: 3448

Iam encountering a 400 Bad Request error during the process.

The issue is with the format or content of the payload sent to Azure DevOps' REST API.

Here, I replicated the same in my environment by following the below steps.

Below is the code to create/generate service endpoint in Azure DevOps.

create_service_endpoint.py:

import requests
from requests.auth import HTTPBasicAuth
import json

# Load configurations from the config file
with open("config.json", "r") as config_file:
    config = json.load(config_file)

AZURE_ORGANIZATION = config["azure_organization"]
AZURE_PROJECT = config["azure_project"]
AZURE_DEVOPS_PAT = config["azure_devops_pat"]
GITLAB_REPO_URL = config["gitlab_repo_url"]
GITLAB_USERNAME = config["gitlab_username"]
GITLAB_PERSONAL_ACCESS_TOKEN = config["gitlab_personal_access_token"]
SERVICE_ENDPOINT_NAME = config["service_endpoint_name"]

# Service Endpoint API URL
service_endpoint_url = f"https://dev.azure.com/{AZURE_ORGANIZATION}/{AZURE_PROJECT}/_apis/serviceendpoint/endpoints?api-version=6.0-preview.4"

# Service Endpoint Payload
service_endpoint_payload = {
    "authorization": {
        "scheme": "UsernamePassword",
        "parameters": {
            "username": GITLAB_USERNAME,
            "password": GITLAB_PERSONAL_ACCESS_TOKEN
        }
    },
    "data": {"accessExternalGitServer": "true"},
    "name": SERVICE_ENDPOINT_NAME,
    "serviceEndpointProjectReferences": [
        {
            "description": "",
            "name": SERVICE_ENDPOINT_NAME,
            "projectReference": {
                "id": AZURE_PROJECT,
                "name": AZURE_PROJECT
            }
        }
    ],
    "type": "git",
    "url": GITLAB_REPO_URL,
    "isShared": False,
    "owner": "library"
}

# Request Headers
headers = {"Content-Type": "application/json"}

# Create Service Endpoint
response = requests.post(
    service_endpoint_url,
    auth=HTTPBasicAuth("", AZURE_DEVOPS_PAT),
    headers=headers,
    data=json.dumps(service_endpoint_payload),
    verify=False
)

# Output Results
if response.status_code in [200, 201]:
    service_endpoint_id = response.json()["id"]
    print(f"Service Endpoint created successfully. ID: {service_endpoint_id}")
else:
    print(f"Failed to create Service Endpoint. Status Code: {response.status_code}")
    print(response.text)

Generate a PAT in Azure DevOps with permissions for Service Connections and Code (Read & Write).

enter image description here

Here is my Gitlab repository and I need to generate PAT in Gitlab also.

enter image description here

enter image description here

The Service Endpoint is created successfully, and its ID is returned.

The Repository Import request succeeds, and the repository is imported into Azure DevOps.

Service Endpoint created successfully.
Response:
{
    "id": "12345678-abcd-1234-efgh-1234567890ab",
    "name": "GitLab Service Connection",
    "type": "git",
    "url": "https://gitlab.com/XXXXXxxx/XXXXX.git",
    "authorization": {
        "scheme": "UsernamePassword",
        "parameters": {
            "username": "your-gitlab-username"
        }
    }
}

HTTP 202 Accepted

Repository import initiated successfully.
Response:
{
    "id": 42,
    "status": "queued",
    "repository": {
        "id": "abcdef12-3456-7890-abcd-ef1234567890",
        "name": "XXXXXXXXX",
        "url": "https://dev.azure.com/MyOrg/MyProject/_git/Stackoverflow"
    }
}

Upvotes: 0

Related Questions