Code Examples & Integration
This page provides practical code examples to help you integrate Aspire Code AI services into your applications quickly and efficiently.
Getting Projects List
Python
import requests
api_key = "your_api_key_here"
base_url = "https://api.aspirecodeai.com/v1"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
try:
response = requests.get(f"{base_url}/projects", headers=headers)
response.raise_for_status()
projects = response.json()
print(f"Found {len(projects)} projects:")
for project in projects:
print(f"- {project['name']} (ID: {project['id']})")
except requests.exceptions.RequestException as e:
print(f"Error: {e}")
JavaScript (Node.js)
const fetch = require('node-fetch');
const apiKey = 'your_api_key_here';
const baseUrl = 'https://api.aspirecodeai.com/v1';
const headers = {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
};
async function getProjects() {
try {
const response = await fetch(`${baseUrl}/projects`, { headers });
if (!response.ok) {
throw new Error(`API Error: ${response.status}`);
}
const projects = await response.json();
console.log(`Found ${projects.length} projects:`);
projects.forEach(project => {
console.log(`- ${project.name} (ID: ${project.id})`);
});
} catch (error) {
console.error('Error:', error.message);
}
}
getProjects();
JavaScript (Browser/Fetch API)
const apiKey = 'your_api_key_here';
const baseUrl = 'https://api.aspirecodeai.com/v1';
const headers = {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
};
fetch(`${baseUrl}/projects`, { headers })
.then(response => {
if (!response.ok) {
throw new Error(`API Error: ${response.status}`);
}
return response.json();
})
.then(projects => {
console.log(`Found ${projects.length} projects`);
projects.forEach(project => {
console.log(`- ${project.name}`);
});
})
.catch(error => {
console.error('Error:', error.message);
});
Creating a New Project
Python
import requests
import json
api_key = "your_api_key_here"
base_url = "https://api.aspirecodeai.com/v1"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
project_data = {
"name": "My AI Project",
"description": "A machine learning application",
"stack": "python",
"framework": "fastapi",
"environment": "development"
}
try:
response = requests.post(
f"{base_url}/projects",
headers=headers,
json=project_data
)
response.raise_for_status()
new_project = response.json()
print(f"Project created successfully!")
print(f"Project ID: {new_project['id']}")
print(f"Project Name: {new_project['name']}")
except requests.exceptions.RequestException as e:
print(f"Error: {e}")
JavaScript (Node.js)
const fetch = require('node-fetch');
const apiKey = 'your_api_key_here';
const baseUrl = 'https://api.aspirecodeai.com/v1';
const headers = {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
};
const projectData = {
name: 'My AI Project',
description: 'A machine learning application',
stack: 'python',
framework: 'fastapi',
environment: 'development'
};
async function createProject() {
try {
const response = await fetch(`${baseUrl}/projects`, {
method: 'POST',
headers,
body: JSON.stringify(projectData)
});
if (!response.ok) {
throw new Error(`API Error: ${response.status}`);
}
const newProject = await response.json();
console.log('Project created successfully!');
console.log(`Project ID: ${newProject.id}`);
console.log(`Project Name: ${newProject.name}`);
} catch (error) {
console.error('Error:', error.message);
}
}
createProject();
Error Handling & Retry Logic
Python with Retry
import requests
import time
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
def create_session_with_retries():
session = requests.Session()
retry_strategy = Retry(
total=3,
backoff_factor=1,
status_forcelist=[429, 500, 502, 503, 504],
)
adapter = HTTPAdapter(max_retries=retry_strategy)
session.mount("http://", adapter)
session.mount("https://", adapter)
return session
api_key = "your_api_key_here"
session = create_session_with_retries()
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
try:
response = session.get(
"https://api.aspirecodeai.com/v1/projects",
headers=headers,
timeout=10
)
response.raise_for_status()
projects = response.json()
print(f"Success: Retrieved {len(projects)} projects")
except requests.exceptions.RequestException as e:
print(f"Error after retries: {e}")
Async/Await Example
Python with Async
import aiohttp
import asyncio
async def fetch_projects():
api_key = "your_api_key_here"
base_url = "https://api.aspirecodeai.com/v1"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
async with aiohttp.ClientSession() as session:
try:
async with session.get(
f"{base_url}/projects",
headers=headers,
timeout=aiohttp.ClientTimeout(total=10)
) as response:
if response.status == 200:
projects = await response.json()
print(f"Retrieved {len(projects)} projects")
return projects
else:
print(f"Error: {response.status}")
except asyncio.TimeoutError:
print("Request timed out")
except Exception as e:
print(f"Error: {e}")
# Run the async function
asyncio.run(fetch_projects())
Complete Integration Example
Full Project Setup (Python)
# Save as: .env
API_KEY=your_api_key_here
BASE_URL=https://api.aspirecodeai.com/v1
# Save as: aspire_client.py
import os
import requests
from dotenv import load_dotenv
load_dotenv()
class AspireClient:
def __init__(self):
self.api_key = os.getenv('API_KEY')
self.base_url = os.getenv('BASE_URL')
self.headers = {
'Authorization': f'Bearer {self.api_key}',
'Content-Type': 'application/json'
}
def get_projects(self):
response = requests.get(
f'{self.base_url}/projects',
headers=self.headers
)
return response.json()
def create_project(self, name, description):
data = {'name': name, 'description': description}
response = requests.post(
f'{self.base_url}/projects',
headers=self.headers,
json=data
)
return response.json()
# Usage
client = AspireClient()
projects = client.get_projects()
print(projects)
Resources & Templates
← Back to Documentation