使用Ubuntu上的GitLab API可按以下步骤操作:
获取访问令牌
登录GitLab账户,进入「Settings」→「Access Tokens」,填写名称、过期时间并选择权限范围,生成令牌。
安装工具与库
curl
(用于命令行请求):sudo apt update && sudo apt install curl
python-gitlab
或requests
):pip install python-gitlab requests
使用API请求
命令行(curl)示例:
curl --header "PRIVATE-TOKEN: your_access_token" "https://gitlab.example.com/api/v4/projects"
curl --request POST --header "PRIVATE-TOKEN: your_access_token" \
--form "branch=main" --form "commit_message=Add file" \
--form "file_path=path/to/file.txt" --form "content=file_content" \
"https://gitlab.example.com/api/v4/projects/{project_id}/repository/files"
Python代码示例:
python-gitlab
库获取项目信息:import gitlab
gl = gitlab.Gitlab('https://gitlab.example.com', private_token='your_access_token')
project = gl.projects.get('project_id')
print(project.name)
requests
库创建提交:import requests
url = "https://gitlab.example.com/api/v4/projects/{project_id}/repository/commits"
headers = {"PRIVATE-TOKEN": "your_access_token"}
data = {
"branch": "main",
"commit_message": "Update file",
"actions": [{"action": "update", "file_path": "README.md", "content": "New content"}]
}
response = requests.post(url, headers=headers, json=data)
print(response.json())
注意事项
api
或write_repository
权限)。