This deliverable provides comprehensive, production-ready code to facilitate integration with external APIs. As the first step in our "API Integration Builder" workflow, this output focuses on generating a robust, flexible, and well-structured codebase that can be adapted to various API requirements.
The generated code is designed with best practices in mind, including modularity, error handling, configuration management, and clear documentation. While a specific example API (Product Catalog API) is used for demonstration, the underlying patterns and components are highly reusable.
Before diving into the code, it's essential to understand the fundamental principles guiding effective API integration:
To provide a concrete and actionable example, we will generate code to integrate with a hypothetical "Product Catalog API". This API manages product information, allowing for common CRUD (Create, Read, Update, Delete) operations.
Hypothetical API Details:
https://api.example.com/products/v1X-API-KEY).Key Endpoints to Integrate:
GET /products: Retrieve a list of all products.GET /products/{id}: Retrieve a single product by its ID.POST /products: Create a new product.PUT /products/{id}: Update an existing product.DELETE /products/{id}: Delete a product.For this example, we have chosen Python due to its:
requests simplify HTTP interactions.The following code is structured into several files for clarity, modularity, and adherence to best practices.
config.pyThis file handles environment-specific configurations, such as API keys and base URLs. Using environment variables is the recommended approach for sensitive data in production.
--- #### 3. `product_catalog_api.py` This file defines the `ProductCatalogAPI` client, which inherits from `HttpClient` and provides specific methods for interacting with the Product Catalog API's endpoints. This separation makes the code cleaner and easier to maintain.
python
from typing import List, Dict, Any, Optional
from api_client_base import HttpClient, APIError
from config import APIConfig
class ProductCatalogAPI:
"""
Client for interacting with the Product Catalog API.
"""
def __init__(self):
# Initialize HttpClient with base URL and required headers (e.g., API Key)
headers = {
"Content-Type": "application/json",
This document provides the generated code and detailed instructions for integrating with an external API to create a project. This deliverable fulfills Step 2 of 2 in the "API Integration Builder" workflow, focusing on the projectmanager → create_project functionality.
The primary goal of this step is to enable your system to programmatically create new projects within an external Project Management System (PMS) via its API. This integration allows for automation of project setup, ensuring consistency and reducing manual effort.
This document includes:
create_project.Since a specific external API was not provided, we have made the following common assumptions regarding the create_project API endpoint:
Authorization header.create_projectBelow is an example specification for the create_project endpoint we are integrating with. This mirrors a common structure found in OpenAPI/Swagger documentation.
Endpoint:
POST /api/v1/projects
Description:
Creates a new project in the external Project Management System.
Request Headers:
Content-Type: application/jsonAuthorization: Bearer YOUR_API_KEY_OR_TOKEN (or X-API-Key: YOUR_API_KEY)Request Body (JSON Example):
{
"name": "New Website Redesign Project",
"description": "Redesign the company website to improve user experience and conversion rates.",
"startDate": "2023-10-26",
"endDate": "2024-03-31",
"status": "Planned",
"priority": "High",
"ownerId": "user-12345",
"budget": {
"amount": 50000,
"currency": "USD"
},
"tags": ["website", "marketing", "redesign"]
}
Response Status Codes:
201 Created: Project successfully created.400 Bad Request: Invalid input data (e.g., missing required fields, invalid date format).401 Unauthorized: Missing or invalid authentication credentials.403 Forbidden: Authenticated user does not have permission to create projects.409 Conflict: A project with the same name or identifier already exists.500 Internal Server Error: An unexpected error occurred on the API server.Successful Response Body (JSON Example - 201 Created):
{
"id": "proj-67890",
"name": "New Website Redesign Project",
"description": "Redesign the company website to improve user experience and conversion rates.",
"startDate": "2023-10-26",
"endDate": "2024-03-31",
"status": "Planned",
"priority": "High",
"ownerId": "user-12345",
"budget": {
"amount": 50000,
"currency": "USD"
},
"tags": ["website", "marketing", "redesign"],
"createdAt": "2023-10-26T10:30:00Z",
"updatedAt": "2023-10-26T10:30:00Z",
"url": "https://pms.example.com/projects/proj-67890"
}
Here are code examples in various languages to interact with the assumed create_project API endpoint.
This example uses the requests library, which is standard for HTTP requests in Python.
import requests
import json
import os
def create_project(project_data: dict) -> dict:
"""
Integrates with an external API to create a new project.
Args:
project_data (dict): A dictionary containing project details.
Example: {
"name": "Project Alpha",
"description": "Description for Project Alpha",
"startDate": "2023-11-01",
"endDate": "2024-01-31",
"status": "Planned",
"priority": "Medium",
"ownerId": "user-abc"
}
Returns:
dict: The response body from the API if the project is created successfully,
or an error dictionary if the API call fails.
"""
# --- Configuration ---
# It's highly recommended to store sensitive information like API keys
# in environment variables, not directly in code.
API_BASE_URL = os.getenv("PMS_API_BASE_URL", "https://api.pms.example.com/v1")
API_KEY = os.getenv("PMS_API_KEY", "YOUR_SECURE_API_KEY_HERE") # Replace with your actual API key
# --- Endpoint and Headers ---
endpoint = f"{API_BASE_URL}/projects"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {API_KEY}" # Or "X-API-Key": API_KEY depending on API
}
print(f"Attempting to create project at: {endpoint}")
print(f"Project data: {json.dumps(project_data, indent=2)}")
try:
response = requests.post(endpoint, headers=headers, json=project_data, timeout=10)
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
print(f"Project creation successful! Status Code: {response.status_code}")
return response.json()
except requests.exceptions.HTTPError as http_err:
print(f"HTTP error occurred: {http_err}")
print(f"Response Status Code: {response.status_code}")
try:
error_details = response.json()
print(f"Error Details: {json.dumps(error_details, indent=2)}")
return {"error": str(http_err), "details": error_details, "status_code": response.status_code}
except json.JSONDecodeError:
print(f"Non-JSON error response: {response.text}")
return {"error": str(http_err), "details": response.text, "status_code": response.status_code}
except requests.exceptions.ConnectionError as conn_err:
print(f"Connection error occurred: {conn_err}")
return {"error": f"Network connection error: {conn_err}"}
except requests.exceptions.Timeout as timeout_err:
print(f"Timeout error occurred: {timeout_err}")
return {"error": f"Request timed out: {timeout_err}"}
except requests.exceptions.RequestException as req_err:
print(f"An unexpected request error occurred: {req_err}")
return {"error": f"An unexpected error: {req_err}"}
except Exception as e:
print(f"An unknown error occurred: {e}")
return {"error": f"Unknown error: {e}"}
# --- Example Usage ---
if __name__ == "__main__":
# Simulate setting environment variables for demonstration
os.environ["PMS_API_BASE_URL"] = "https://api.pms.example.com/v1"
os.environ["PMS_API_KEY"] = "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # Replace with your actual key
new_project_details = {
"name": "PantheraHive AI Integration Project",
"description": "Integrate PantheraHive AI services into existing project workflows.",
"startDate": "2023-11-01",
"endDate": "2024-02-28",
"status": "Planned",
"priority": "High",
"ownerId": "ph-admin-001",
"budget": {
"amount": 75000,
"currency": "USD"
},
"tags": ["AI", "integration", "workflow"]
}
created_project = create_project(new_project_details)
if "error" in created_project:
print("\nFailed to create project:")
print(json.dumps(created_project, indent=2))
else:
print("\nSuccessfully created project:")
print(json.dumps(created_project, indent=2))
print(f"New Project ID: {created_project.get('id', 'N/A')}")
This example uses the built-in fetch API available in Node.js (v18+) or client-side JavaScript. For older Node.js versions, consider using libraries like node-fetch or axios.
// projectManager.js
const fetch = require('node-fetch'); // For Node.js versions < 18, install 'node-fetch'
// For Node.js >= 18, 'fetch' is global, no need to require it.
// If using client-side JavaScript, 'fetch' is globally available.
// It's highly recommended to store sensitive information like API keys
// in environment variables, not directly in code.
const PMS_API_BASE_URL = process.env.PMS_API_BASE_URL || "https://api.pms.example.com/v1";
const PMS_API_KEY = process.env.PMS_API_KEY || "YOUR_SECURE_API_KEY_HERE"; // Replace with your actual API key
/**
* Integrates with an external API to create a new project.
* @param {object} projectData - An object containing project details.
* Example: {
* name: "Project Beta",
* description: "Description for Project Beta",
* startDate: "2023-12-01",
* endDate: "2024-03-31",
* status: "In Progress",
* priority: "High",
* ownerId: "user-xyz"
* }
* @returns {Promise<object>} A promise that resolves with the API response body
* or rejects with an error object.
*/
async function createProject(projectData) {
const endpoint = `${PMS_API_BASE_URL}/projects`;
const headers = {
"Content-Type": "application/json",
"Authorization": `Bearer ${PMS_API_KEY}` // Or "X-API-Key": PMS_API_KEY
};
console.log(`Attempting to create project at: ${endpoint}`);
console.log(`Project data: ${JSON.stringify(projectData, null, 2)}`);
try {
const response = await fetch(endpoint, {
method: 'POST',
headers: headers,
body: JSON.stringify(projectData),
timeout: 10000 // Timeout in milliseconds (not directly supported by standard fetch, might need AbortController for actual timeout)
});
if (!response.ok) {
let errorDetails = `HTTP error! Status: ${response.status}`;
try {
const errorBody = await response.json();
errorDetails += ` Details: ${JSON.stringify(errorBody, null, 2)}`;
console.error(`API Error: ${errorDetails}`);
throw new Error(errorDetails);
} catch (jsonError) {
const errorText = await response.text();
errorDetails += ` Response Text: ${errorText}`;
console.error(`API Error (non-JSON response): ${errorDetails}`);
throw new Error(errorDetails);
}
}
console.log(`Project creation successful! Status Code: ${response.status}`);
return await response.json();
} catch (error) {
console.error(`An error occurred during project creation: ${error.message}`);
// For actual network errors (e.g., DNS resolution, connection refused),
// the error object might not have a 'response' property.
throw {
message: `Failed to create project: ${error.message}`,
details: error.response ? await error.response.json() : error.message
};
}
}
// --- Example Usage ---
(async () => {
// Simulate setting environment variables for demonstration
process.env.PMS_API_BASE_URL = "https://api.pms.example.com/v1";
process.env.PMS_API_KEY = "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // Replace with your actual key
const newProjectDetails = {
"name": "Customer Feedback System Development",
"description": "Build a new system to collect, analyze, and act on customer feedback.",
"startDate": "2023-11-15",
"endDate": "2024-05-31",
"status": "Planned",
"priority": "Critical",
"ownerId": "dev-lead-002",
"budget": {
"amount": 120000,
"currency": "USD"
},
"tags": ["feedback", "customer", "development"]
};
try {
const createdProject = await createProject(newProjectDetails);
console.log("\nSuccessfully created project:");
console.log(JSON.stringify(createdProject, null, 2));
console.log(`New Project ID: ${createdProject?.id || 'N/A'}`);
} catch (error) {
console.error("\nFailed to create project:");
console.error(JSON.stringify(error, null, 2));
}
})();
cURL is a command-line tool for making HTTP requests and is excellent for quick testing and debugging API endpoints.
# Replace YOUR_SECURE_API_KEY_HERE with your actual API key
# Replace https://api.pms.example.com/v1 with the actual API base URL
curl -X POST \
https://api.pms.example.com/v1/projects \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer YOUR_SECURE_API_KEY_HERE' \
-d '{
"name": "Internal Tools Improvement Project",
"description": "Enhance internal tools for better team productivity and efficiency.",
"startDate": "2023-12-01",
\n