GitCode API Usage Guide
GitCode API Usage Guide
GitCode AI community provides complete API interfaces and command-line tools, allowing you to access various platform functions programmatically. This guide will详细介绍 how to use GitCode CLI tools and API interfaces.
GitCode CLI Tools
Installation and Configuration
1. Install CLI Tools
# Install using pip
pip install gitcode
# Install using conda
conda install -c conda-forge gitcode
# Install from source
git clone https://github.com/gitcode-ai/gitcode-cli.git
cd gitcode-cli
pip install -e .
2. Configure Authentication
# Login to account
gitcode login
# Set API Token
gitcode config set api_token YOUR_API_TOKEN
# View configuration
gitcode config list
# Set default organization
gitcode config set organization your-org-name
3. Verify Installation
# Check version
gitcode --version
# Check connection status
gitcode status
# View help information
gitcode --help
Model Management Commands
1. Model Search and Browse
# Search models
gitcode search models "bert chinese"
# Search by tags
gitcode search models --tags nlp,chinese
# Search by framework
gitcode search models --framework pytorch
# Search by task type
gitcode search models --task text-classification
# View model details
gitcode models show username/model-name
# List all models by user
gitcode models list --user username
2. Model Download
# Download model
gitcode models download username/model-name
# Download specific version
gitcode models download username/model-name --version v1.0.0
# Download to specified directory
gitcode models download username/model-name --output ./models/
# Download model configuration only
gitcode models download username/model-name --config-only
# Batch download
gitcode models download username/model1 username/model2
3. Model Upload and Publishing
# Create new model
gitcode models create --name my-model --description "Model description"
# Upload model files
gitcode models upload username/model-name --file model.pth
# Publish model version
gitcode models publish username/model-name --version v1.0.0
# Update model information
gitcode models update username/model-name --description "New description"
# Delete model
gitcode models delete username/model-name --force
4. Model Version Management
# View version history
gitcode models versions username/model-name
# Create new version
gitcode models versions create username/model-name --version v1.1.0
# Delete version
gitcode models versions delete username/model-name --version v1.0.0
# Set default version
gitcode models versions set-default username/model-name --version v1.0.0
Dataset Management Commands
1. Dataset Search and Browse
# Search datasets
gitcode search datasets "image classification"
# Search by type
gitcode search datasets --type image
# Search by license
gitcode search datasets --license mit
# View dataset details
gitcode datasets show username/dataset-name
# List user's datasets
gitcode datasets list --user username
2. Dataset Download
# Download dataset
gitcode datasets download username/dataset-name
# Download specific version
gitcode datasets download username/dataset-name --version v1.0.0
# Download partial data
gitcode datasets download username/dataset-name --subset train
# Download to specified directory
gitcode datasets download username/dataset-name --output ./data/
# Verify download integrity
gitcode datasets download username/dataset-name --verify
3. Dataset Upload and Publishing
# Create new dataset
gitcode datasets create --name my-dataset --description "Dataset description"
# Upload data files
gitcode datasets upload username/dataset-name --file data.zip
# Publish dataset
gitcode datasets publish username/dataset-name --version v1.0.0
# Update dataset information
gitcode datasets update username/dataset-name --description "New description"
# Set dataset visibility
gitcode datasets update username/dataset-name --visibility public
Space Application Management
1. Space Application Operations
# Search Space applications
gitcode search spaces "text generation"
# View application details
gitcode spaces show username/space-name
# Start application
gitcode spaces start username/space-name
# Stop application
gitcode spaces stop username/space-name
# View application status
gitcode spaces status username/space-name
# View application logs
gitcode spaces logs username/space-name
2. Space Application Deployment
# Create new Space
gitcode spaces create --name my-app --description "Application description"
# Deploy application code
gitcode spaces deploy username/space-name --source ./app/
# Set environment variables
gitcode spaces env set username/space-name --key API_KEY --value your-api-key
# View environment variables
gitcode spaces env list username/space-name
# Delete environment variables
gitcode spaces env delete username/space-name --key API_KEY
Notebook Environment Management
1. Notebook Operations
# Create Notebook
gitcode notebooks create --name my-notebook
# Start Notebook environment
gitcode notebooks start notebook-id
# Stop Notebook environment
gitcode notebooks stop notebook-id
# View Notebook status
gitcode notebooks status notebook-id
# Delete Notebook
gitcode notebooks delete notebook-id
2. File Management
# Upload files to Notebook
gitcode notebooks upload notebook-id --file ./data.csv
# Download Notebook files
gitcode notebooks download notebook-id --file notebook.ipynb
# List Notebook files
gitcode notebooks files notebook-id
# Delete Notebook files
gitcode notebooks delete-file notebook-id --file data.csv
REST API Interfaces
Authentication and Authorization
1. API Token Authentication
import requests
# Set API Token
API_TOKEN = "your_api_token_here"
headers = {
"Authorization": f"Bearer {API_TOKEN}",
"Content-Type": "application/json"
}
# Base URL
BASE_URL = "https://api.gitcode.com/v1"
2. Get User Information
def get_user_info():
"""Get current user information"""
response = requests.get(f"{BASE_URL}/user", headers=headers)
return response.json()
# Usage example
user_info = get_user_info()
print(f"Username: {user_info['username']}")
print(f"Email: {user_info['email']}")
Model API
1. Model Search
def search_models(query, filters=None):
"""Search models"""
params = {"q": query}
if filters:
params.update(filters)
response = requests.get(f"{BASE_URL}/models/search",
headers=headers, params=params)
return response.json()
# Usage example
# Search for Chinese BERT models
models = search_models("bert chinese", {
"framework": "pytorch",
"task": "text-classification",
"language": "chinese"
})
for model in models['results']:
print(f"Model: {model['name']}")
print(f"Description: {model['description']}")
print(f"Downloads: {model['downloads']}")
2. Model Details
def get_model_info(model_id):
"""Get detailed model information"""
response = requests.get(f"{BASE_URL}/models/{model_id}", headers=headers)
return response.json()
def get_model_versions(model_id):
"""Get model version information"""
response = requests.get(f"{BASE_URL}/models/{model_id}/versions",
headers=headers)
return response.json()
# Usage example
model_info = get_model_info("username/model-name")
versions = get_model_versions("username/model-name")
print(f"Model name: {model_info['name']}")
print(f"Latest version: {model_info['latest_version']}")
print(f"Total downloads: {model_info['total_downloads']}")
3. Model Download
def download_model(model_id, version=None, output_path="./"):
"""Download model"""
# Get download link
params = {}
if version:
params["version"] = version
response = requests.get(f"{BASE_URL}/models/{model_id}/download",
headers=headers, params=params)
download_info = response.json()
# Download file
download_url = download_info['download_url']
file_response = requests.get(download_url, stream=True)
filename = download_info['filename']
filepath = os.path.join(output_path, filename)
with open(filepath, 'wb') as f:
for chunk in file_response.iter_content(chunk_size=8192):
f.write(chunk)
return filepath
# Usage example
model_path = download_model("username/model-name", version="v1.0.0")
print(f"Model downloaded to: {model_path}")
4. Model Upload
def create_model(model_data):
"""Create new model"""
response = requests.post(f"{BASE_URL}/models",
headers=headers, json=model_data)
return response.json()
def upload_model_file(model_id, file_path, version="v1.0.0"):
"""Upload model file"""
with open(file_path, 'rb') as f:
files = {'file': f}
data = {'version': version}
response = requests.post(f"{BASE_URL}/models/{model_id}/upload",
headers=headers, files=files, data=data)
return response.json()
# Usage example
# Create model
model_data = {
"name": "my-bert-model",
"description": "Chinese BERT text classification model",
"framework": "pytorch",
"task": "text-classification",
"tags": ["bert", "chinese", "nlp"]
}
new_model = create_model(model_data)
print(f"Model created successfully: {new_model['id']}")
# Upload model file
upload_result = upload_model_file(new_model['id'], "./model.pth")
print(f"File upload successful: {upload_result['message']}")
Dataset API
1. Dataset Search
def search_datasets(query, filters=None):
"""Search datasets"""
params = {"q": query}
if filters:
params.update(filters)
response = requests.get(f"{BASE_URL}/datasets/search",
headers=headers, params=params)
return response.json()
# Usage example
datasets = search_datasets("image classification", {
"type": "image",
"license": "mit",
"size": "small"
})
for dataset in datasets['results']:
print(f"Dataset: {dataset['name']}")
print(f"Size: {dataset['size']}")
print(f"Sample count: {dataset['sample_count']}")
2. Dataset Download
def download_dataset(dataset_id, version=None, subset=None):
"""Download dataset"""
params = {}
if version:
params["version"] = version
if subset:
params["subset"] = subset
response = requests.get(f"{BASE_URL}/datasets/{dataset_id}/download",
headers=headers, params=params)
return response.json()
# Usage example
download_info = download_dataset("username/dataset-name",
version="v1.0.0",
subset="train")
print(f"Download link: {download_info['download_url']}")
Space API
1. Space Application Operations
def get_space_info(space_id):
"""Get Space information"""
response = requests.get(f"{BASE_URL}/spaces/{space_id}", headers=headers)
return response.json()
def start_space(space_id):
"""Start Space application"""
response = requests.post(f"{BASE_URL}/spaces/{space_id}/start",
headers=headers)
return response.json()
def stop_space(space_id):
"""Stop Space application"""
response = requests.post(f"{BASE_URL}/spaces/{space_id}/stop",
headers=headers)
return response.json()
# Usage example
space_info = get_space_info("username/space-name")
print(f"Application status: {space_info['status']}")
if space_info['status'] == 'stopped':
start_result = start_space("username/space-name")
print(f"Start result: {start_result['message']}")
2. Space Application API Calls
def call_space_api(space_id, endpoint, data=None):
"""Call Space application API"""
url = f"{BASE_URL}/spaces/{space_id}/api/{endpoint}"
if data:
response = requests.post(url, headers=headers, json=data)
else:
response = requests.get(url, headers=headers)
return response.json()
# Usage example
# Call text generation API
result = call_space_api("username/text-generator", "generate", {
"prompt": "Today's weather is nice",
"max_length": 100
})
print(f"Generated result: {result['generated_text']}")
Notebook API
1. Notebook Environment Management
def create_notebook(notebook_data):
"""Create Notebook"""
response = requests.post(f"{BASE_URL}/notebooks",
headers=headers, json=notebook_data)
return response.json()
def start_notebook(notebook_id):
"""Start Notebook environment"""
response = requests.post(f"{BASE_URL}/notebooks/{notebook_id}/start",
headers=headers)
return response.json()
def get_notebook_status(notebook_id):
"""Get Notebook status"""
response = requests.get(f"{BASE_URL}/notebooks/{notebook_id}/status",
headers=headers)
return response.json()
# Usage example
notebook_data = {
"name": "my-experiment",
"description": "Machine learning experiment",
"environment": "python3.9",
"resources": {
"cpu": 2,
"memory": "4Gi",
"gpu": 1
}
}
new_notebook = create_notebook(notebook_data)
print(f"Notebook created successfully: {new_notebook['id']}")
# Start environment
start_result = start_notebook(new_notebook['id'])
print(f"Start result: {start_result['message']}")
Error Handling and Retry
Common Error Codes
1. HTTP Status Codes
# Common status code handling
def handle_response(response):
"""Handle API response"""
if response.status_code == 200:
return response.json()
elif response.status_code == 401:
raise Exception("Authentication failed, please check API Token")
elif response.status_code == 403:
raise Exception("Insufficient permissions, cannot access this resource")
elif response.status_code == 404:
raise Exception("Requested resource does not exist")
elif response.status_code == 429:
raise Exception("Request frequency too high, please try again later")
elif response.status_code >= 500:
raise Exception("Server internal error, please try again later")
else:
raise Exception(f"Unknown error: {response.status_code}")
2. Retry Mechanism
import time
from functools import wraps
def retry_on_error(max_retries=3, delay=1):
"""Retry decorator"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(max_retries):
try:
return func(*args, **kwargs)
except Exception as e:
if attempt == max_retries - 1:
raise e
print(f"Attempt {attempt + 1} failed, retrying in {delay} seconds...")
time.sleep(delay)
return None
return wrapper
return decorator
# Use retry mechanism
@retry_on_error(max_retries=3, delay=2)
def api_call_with_retry():
"""API call with retry"""
response = requests.get(f"{BASE_URL}/models/search", headers=headers)
return handle_response(response)
Best Practices
Performance Optimization
1. Batch Operations
def batch_download_models(model_ids, output_dir="./models"):
"""Batch download models"""
results = []
for model_id in model_ids:
try:
result = download_model(model_id, output_path=output_dir)
results.append({"model_id": model_id, "status": "success", "path": result})
except Exception as e:
results.append({"model_id": model_id, "status": "failed", "error": str(e)})
return results
# Usage example
model_ids = ["user1/model1", "user2/model2", "user3/model3"]
download_results = batch_download_models(model_ids)
2. Asynchronous Processing
import asyncio
import aiohttp
async def async_download_model(session, model_id, output_path):
"""Asynchronously download model"""
async with session.get(f"{BASE_URL}/models/{model_id}/download",
headers=headers) as response:
download_info = await response.json()
async with session.get(download_info['download_url']) as file_response:
content = await file_response.read()
with open(output_path, 'wb') as f:
f.write(content)
return output_path
async def download_multiple_models(model_ids, output_dir):
"""Asynchronously download multiple models"""
async with aiohttp.ClientSession() as session:
tasks = []
for model_id in model_ids:
filename = f"{model_id.replace('/', '_')}.pth"
output_path = os.path.join(output_dir, filename)
task = async_download_model(session, model_id, output_path)
tasks.append(task)
results = await asyncio.gather(*tasks, return_exceptions=True)
return results
# Usage example
model_ids = ["user1/model1", "user2/model2", "user3/model3"]
results = asyncio.run(download_multiple_models(model_ids, "./models"))
Resource Management
1. Connection Pool Management
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
def create_session():
"""Create optimized session"""
session = requests.Session()
# Configure retry strategy
retry_strategy = Retry(
total=3,
backoff_factor=1,
status_forcelist=[429, 500, 502, 503, 504]
)
# Configure connection pool
adapter = HTTPAdapter(
max_retries=retry_strategy,
pool_connections=10,
pool_maxsize=20
)
session.mount("http://", adapter)
session.mount("https://", adapter)
return session
# Use optimized session
session = create_session()
session.headers.update(headers)
# Use session for requests
response = session.get(f"{BASE_URL}/models/search", params={"q": "bert"})
Summary
GitCode CLI tools and API interfaces provide you with powerful programmatic access capabilities:
- CLI Tools: Suitable for daily operations and script automation
- REST API: Suitable for integration into applications
- Batch Operations: Improve work efficiency
- Error Handling: Ensure program stability
- Performance Optimization: Improve execution efficiency
Through reasonable use of these tools, you can:
- Automate model and dataset management workflows
- Build custom AI development tools
- Integrate GitCode functionality into existing systems
- Improve team collaboration efficiency
Remember, when using APIs, pay attention to:
- Reasonably control request frequency
- Safely keep API Token
- Implement appropriate error handling
- Follow platform usage standards
If you need more detailed API documentation or encounter problems, please refer to official documentation or contact technical support team.