### Project JSON Response Example Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/types.md Example of a JSON response when retrieving project details via a GET request. ```json { "project": { "id": 12345, "name": "Brand New Project", "description": "A demo project", "company-id": "123", "category-id": "0", "privacy-enabled": true, "start-date": "20240101", "end-date": "20241231", "created-on": "2024-01-01T10:00:00Z", "updated-on": "2024-01-15T15:30:00Z" } } ``` -------------------------------- ### Go GET Request Usage Example Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/api-reference/go.md Example of how to call the getRequest function with a specific project endpoint. ```go func main() { projectId := "12345" endPoint := "projects/" + projectId + "." + dataPreference getRequest(endPoint) } ``` -------------------------------- ### Complete Node.js Task Management Example Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/api-reference/nodejs.md A comprehensive Node.js example demonstrating task management operations including listing projects, creating, getting, updating, completing, and deleting tasks. Requires the 'request' module. ```javascript var request = require('request'); var config = { company: "mycompany", apiKey: "your_api_key", taskListId: "5100" }; function makeRequest(method, endpoint, body, callback) { var url = "https://" + config.company + ".teamwork.com/" + endpoint; var base64 = new Buffer(config.apiKey + ":xxx").toString("base64"); var options = { url: url, method: method, headers: { "Authorization": "BASIC " + base64, "Content-Type": "application/json" }, json: body || true }; request(options, function(error, response, data) { if (!error && response.statusCode >= 200 && response.statusCode < 300) { callback(null, data); } else { callback(error || "HTTP " + response.statusCode); } }); } // List all projects function listProjects(callback) { makeRequest('GET', 'projects.json', null, callback); } // Create a new task function createTask(content, dueDate, callback) { var body = { "todo-item": { "content": content, "notify": true } }; if (dueDate) { body['todo-item']['due-date'] = dueDate; } var endpoint = "todo_lists/" + config.taskListId + "/todo_items.json"; makeRequest('POST', endpoint, body, callback); } // Get task by ID function getTask(taskId, callback) { makeRequest('GET', 'tasks/' + taskId + '.json', null, callback); } // Update task function updateTask(taskId, updates, callback) { var endpoint = 'tasks/' + taskId + '.json'; makeRequest('PUT', endpoint, { "todo-item": updates }, callback); } // Complete task function completeTask(taskId, callback) { var endpoint = 'tasks/' + taskId + '/complete.json'; makeRequest('PUT', endpoint, null, callback); } // Delete task function deleteTask(taskId, callback) { makeRequest('DELETE', 'tasks/' + taskId + '.json', null, callback); } // Main execution listProjects(function(err, projects) { if (err) { console.error("Error listing projects: " + err); return; } console.log("Projects: " + JSON.stringify(projects, null, 2)); // Create a task createTask("Complete API integration", "20240131", function(err, result) { if (err) { console.error("Error creating task: " + err); return; } var newTaskId = result['todo-item'].id; console.log("Created task ID: " + newTaskId); // Update the task updateTask(newTaskId, { content: "Complete API integration - In Progress" }, function(err, updated) { if (err) { console.error("Error updating task: " + err); } else { console.log("Task updated"); } }); }); }); ``` -------------------------------- ### Usage Example for GET Request Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/api-reference/java.md Demonstrates how to call the `getRequest` method with specific Teamwork API URL, endpoint, and API key to fetch project data. ```java String APIKey = "your_api_key"; String TeamworkURL = "https://mycompany.teamwork.com"; String projectsJson = getRequest(TeamworkURL, "/projects.json", APIKey); System.out.println("Projects: " + projectsJson); ``` -------------------------------- ### Example Usage for POST Request Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/api-reference/go.md This example demonstrates how to prepare the payload and call the `postRequest` function to create a new project. ```go func main() { data := &ProjectJson{ Project: Project{ Category_id: "0", CompanyID: companyId, Description: "A demo project", EndDate: "", Harvest_timers_enabled: true, Name: "Brand New Project", NewCompany: "", PrivacyEnabled: true, ReplyByEmailEnabled: true, StartDate: "", }, } postRequest("projects.json", data) } ``` -------------------------------- ### Go Date Conversion Examples Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/types.md Provides examples for parsing and formatting dates in Go, including handling ISO 8601 timestamps. ```Go import "time" // String to date dateStr := "20240115" dateObj, _ := time.Parse("20060102", dateStr) // Date to string dateObj := time.Now() dateStr := dateObj.Format("20060102") // ISO datetime isoStr := "2024-01-15T15:30:00Z" datetimeObj, _ := time.Parse(time.RFC3339, isoStr) ``` -------------------------------- ### URL Construction Examples Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/configuration.md Provides concrete examples of fully formed API request URLs for various endpoints. ```Text https://mycompany.teamwork.com/projects.json https://mycompany.teamwork.com/projects/123.json https://mycompany.teamwork.com/todo_lists/5100/todo_items.json https://mycompany.teamwork.com/projects/123/messages.json https://mycompany.teamwork.com/tasks/67890.json https://mycompany.teamwork.com/pendingfiles.json ``` -------------------------------- ### Example Usage of GET Request Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/api-reference/python.md Demonstrates how to call the get_request function to retrieve all projects from the Teamwork API and print the response. ```python # Retrieve all projects company = "mycompany" api_key = "your_api_key_here" try: projects = get_request(company, api_key, "projects.json") print(json.dumps(projects, indent=2)) except Exception as e: print("Error: {0}".format(e)) ``` -------------------------------- ### Example Usage for PUT Request Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/api-reference/go.md This example shows how to construct the endpoint URL with a project ID and prepare the updated project data to call the `putRequest` function. ```go func main() { projectId := "12345" data := &ProjectJson{ Project: Project{ Category_id: "0", CompanyID: companyId, Description: "Edited project", EndDate: "", Harvest_timers_enabled: true, Name: "Edited New Project", NewCompany: "", PrivacyEnabled: true, ReplyByEmailEnabled: true, StartDate: "", }, } endPoint := "projects/" + projectId + ".json" putRequest(endPoint, data) } ``` -------------------------------- ### Get All Projects (PHP) Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/quickstart.md Fetches all projects using PHP. This example utilizes cURL for making the HTTP request. ```php ``` -------------------------------- ### Usage Example for Basic GET Request Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/api-reference/csharp.md This snippet shows how to instantiate the TeamworkAPI class and call the GetData method to retrieve project data. ```csharp var api = new TeamworkAPI(); string projectsJson = await api.GetData(); Console.WriteLine(projectsJson); ``` -------------------------------- ### HTTP GET Request with Basic Authentication (Go) Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/README.md Illustrates making a GET request to fetch projects in Go, utilizing the standard net/http package and base64 encoding for authentication. ```go import "net/http" import "encoding/base64" client := &http.Client{} req, _ := http.NewRequest("GET", "https://mycompany.teamwork.com/projects.json", nil) req.Header.Add("Authorization", "Basic " + base64.StdEncoding.EncodeToString([]byte("api_key:xxx"))) resp, _ := client.Do(req) body, _ := ioutil.ReadAll(resp.Body) ``` -------------------------------- ### Install urllib3 for Python Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/api-reference/python.md Install the urllib3 library for Python 3 or Python 2 using pip. ```bash # Python 3 pip install urllib3 # Python 2 pip install urllib3 ``` -------------------------------- ### GET Request Usage Example Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/api-reference/nodejs.md Example of how to use the `getRequest` function to fetch projects from the Teamwork API. It logs the status code and project data or any errors encountered. ```javascript var company = "mycompany"; var apiKey = "your_api_key_here"; getRequest(company, apiKey, "projects.json", function(error, status, data) { if (error) { console.error("Error: " + error); } else { console.log("Status: " + status); console.log("Projects: " + JSON.stringify(data, null, 2)); } }); ``` -------------------------------- ### Project JSON Request Example Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/types.md Example of a JSON payload for creating or updating a project via POST/PUT requests. ```json { "project": { "name": "Brand New Project", "description": "A demo project", "company-id": "123", "category-id": "0", "privacy-enabled": true, "start-date": "20240101", "end-date": "20241231" } } ``` -------------------------------- ### Install Newtonsoft.Json via Package Manager Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/api-reference/csharp.md Alternatively, install the Newtonsoft.Json package using the Package Manager console. ```powershell Install-Package Newtonsoft.Json ``` -------------------------------- ### JSON Request Body Example Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/quickstart.md Example of a JSON object for a 'todo-item' resource. ```json { "todo-item": { "content": "Task title", "due-date": "20240228" } } ``` -------------------------------- ### Example: Resource Not Found Error (404) Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/errors.md Demonstrates the JSON response for a 404 Not Found error, indicating a non-existent resource. ```json { "error": { "message": "Project not found", "code": "NOT_FOUND", "details": "No project with ID 99999 exists in this company" } } ``` -------------------------------- ### Get All Projects (Python) Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/quickstart.md Fetches a list of all projects for your Teamwork account using Python. Ensure you have the 'urllib3' library installed. ```python import urllib3 import json http = urllib3.PoolManager() company = "mycompany" # Your Teamwork subdomain api_key = "your_api_key_here" url = "https://{}.teamwork.com/projects.json".format(company) headers = urllib3.util.make_headers(basic_auth=api_key + ":xxx") request = http.request('GET', url, headers=headers) if request.status == 200: projects = json.loads(request.data.decode('utf-8')) print(json.dumps(projects, indent=2)) ``` -------------------------------- ### JSON Response Example Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/README.md An example of the JSON structure returned by the API for project-related data. ```json { "project": { "id": 12345, "name": "Project Name", "description": "Description" } } ``` -------------------------------- ### HTTP GET Request with Basic Authentication (Python) Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/README.md Demonstrates how to make a GET request to retrieve projects using Python's urllib3 library and HTTP Basic Authentication. ```python import urllib3, json http = urllib3.PoolManager() url = "https://mycompany.teamwork.com/projects.json" headers = urllib3.util.make_headers(basic_auth="api_key:xxx") response = http.request('GET', url, headers=headers) if response.status == 200: projects = json.loads(response.data.decode('utf-8')) print(projects) ``` -------------------------------- ### Pagination Example Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/endpoints.md Shows how to request a specific page and page size for list endpoints. The response may include pagination metadata. ```HTTP GET /projects.json?page=1&pageSize=25 ``` -------------------------------- ### Go Task Management API Example Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/api-reference/go.md This comprehensive example demonstrates how to create, list, complete, and delete tasks using the Teamwork API in Go. It includes helper functions for authentication and making HTTP requests. ```go package main import ( "bytes" "encoding/base64" "encoding/json" "fmt" "io/ioutil" "log" "net/http" ) const ( siteName string = "mycompany" apiUrl string = "https://" + siteName + ".teamwork.com/" apiKey string = "your_api_key" taskListId string = "5100" ) type TodoItem struct { ID int `json:"id"` Content string `json:"content"` Description string `json:"description"` DueDate string `json:"due-date"` Priority string `json:"priority"` Completed bool `json:"completed"` } type TodoItemRequest struct { Item TodoItem `json:"todo-item"` } func basicAuth(apiKey string) string { return base64.StdEncoding.EncodeToString([]byte(apiKey + ":xxx")) } func makeRequest(method string, endpoint string, body interface{}) ([]byte, error) { /** * Make an HTTP request to the Teamwork API. * * @param method - HTTP method (GET, POST, PUT, DELETE) * @param endpoint - API endpoint path * @param body - Optional request body * @return Response body bytes and error */ var reqBody *bytes.Buffer if body != nil { jsonBody, err := json.Marshal(body) if err != nil { return nil, err } reqBody = bytes.NewBuffer(jsonBody) } url := apiUrl + endpoint req, err := http.NewRequest(method, url, reqBody) if err != nil { return nil, err } req.Header.Add("Authorization", "Basic "+basicAuth(apiKey)) req.Header.Set("Content-Type", "application/json") req.Header.Add("Accept", "application/json") client := &http.Client{} resp, err := client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() respBody, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } if resp.StatusCode < 200 || resp.StatusCode >= 300 { return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(respBody)) } return respBody, nil } func createTask(content string, dueDate string, priority string) (*TodoItem, error) { /** * Create a new task in the task list. * * @param content - Task title * @param dueDate - Due date (YYYYMMDD format) * @param priority - Priority level * @return Created task and error */ request := TodoItemRequest{ Item: TodoItem{ Content: content, DueDate: dueDate, Priority: priority, }, } endpoint := fmt.Sprintf("todo_lists/%s/todo_items.json", taskListId) respBody, err := makeRequest("POST", endpoint, request) if err != nil { return nil, err } var response TodoItemRequest err = json.Unmarshal(respBody, &response) if err != nil { return nil, err } return &response.Item, nil } func listTasks() ([]TodoItem, error) { /** * List all tasks in the task list. * * @return List of tasks and error */ endpoint := fmt.Sprintf("todo_lists/%s.json", taskListId) respBody, err := makeRequest("GET", endpoint, nil) if err != nil { return nil, err } var response map[string][]TodoItem err = json.Unmarshal(respBody, &response) if err != nil { return nil, err } return response["todo-items"], } func completeTask(taskId string) error { /** * Mark a task as complete. * * @param taskId - Task identifier * @return Error if any */ endpoint := fmt.Sprintf("tasks/%s/complete.json", taskId) _, err := makeRequest("PUT", endpoint, nil) return err } func deleteTask(taskId string) error { /** * Delete a task. * * @param taskId - Task identifier * @return Error if any */ endpoint := fmt.Sprintf("tasks/%s.json", taskId) _, err := makeRequest("DELETE", endpoint, nil) return err } func main() { // Create a task task, err := createTask("Complete API integration", "20240131", "high") if err != nil { log.Fatal("Error creating task:", err) } fmt.Printf("Created task ID: %d\n", task.ID) fmt.Printf("Content: %s\n", task.Content) // List all tasks tasks, err := listTasks() if err != nil { log.Fatal("Error listing tasks:", err) } fmt.Printf("Total tasks: %d\n", len(tasks)) for _, t := range tasks { fmt.Printf(" - [%d] %s (Priority: %s)\n", t.ID, t.Content, t.Priority) } // Complete the task err = completeTask(fmt.Sprintf("%d", task.ID)) if err != nil { log.Fatal("Error completing task:", err) } fmt.Println("Task marked as complete") } ``` -------------------------------- ### Install Request Module Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/api-reference/nodejs.md Install the 'request' module using npm. This is required for making HTTP requests in Node.js. ```bash npm install request ``` -------------------------------- ### HTTP GET Request with Basic Authentication (Node.js) Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/README.md Shows how to perform a GET request for projects using Node.js and the 'request' library, including setting up Basic Authentication. ```javascript var request = require('request'); request({ url: 'https://mycompany.teamwork.com/projects.json', method: 'GET', headers: { 'Authorization': 'BASIC ' + Buffer.from('api_key:xxx').toString('base64') }, json: true }, function(error, response, body) { if (!error && response.statusCode == 200) { console.log(body); } }); ``` -------------------------------- ### List Projects using cURL Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/quickstart.md Example of how to list projects using cURL. Requires authentication with your API key. ```bash # List projects curl -u "your_api_key:xxx" https://mycompany.teamwork.com/projects.json ``` -------------------------------- ### Example Usage of DELETE Request Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/api-reference/go.md This is an example of how to call the deleteRequest function. It constructs a project-specific endpoint and initiates the deletion process. ```go func main() { projectId := "12345" endPoint := "projects/" + projectId + ".json" deleteRequest(endPoint) } ``` -------------------------------- ### Example Usage for PUT Request Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/api-reference/java.md This example shows how to call the `putRequest` method to complete a task. It provides the Teamwork base URL, the action endpoint, and an API key. The JSON body is set to null in this case. ```java // Complete a task String response = putRequest( "https://mycompany.teamwork.com", "/tasks/67890/complete.json", "api_key", null ); ``` -------------------------------- ### Java POST Request Usage Example Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/api-reference/java.md This example demonstrates how to use the `postRequest` method to create a new task in a Teamwork project. It shows how to construct the JSON payload and call the method with appropriate parameters. Ensure the `postRequest` method is accessible. ```java Date date = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); String dueDate = dateFormat.format(date); String taskJson = "{" + "\"todo-item\": {" + "\"content\": \"Complete API integration\", ``` ```java + "\"due-date\": \"" + dueDate + "\", ``` ```java + "\"priority\": \"high\"" + "}" + "}"; String response = postRequest( "https://mycompany.teamwork.com", "/todo_lists/5100/todo_items.json", "api_key", taskJson ); ``` -------------------------------- ### Implement Basic GET Request to Teamwork API Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/api-reference/csharp.md This method demonstrates how to perform a GET request to retrieve data from the Teamwork API, including setting up authentication and handling the response. ```csharp using System; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; public class TeamworkAPI { public async Task GetData() { const string apiKey = ""; const string domain = ""; const string endpoint = "projects.json"; var client = new HttpClient { BaseAddress = new Uri("https://" + domain + ".teamwork.com") }; // Set Basic authentication header client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Basic", Convert.ToBase64String( UTF8Encoding.UTF8.GetBytes( string.Format("{0}:{1}", apiKey, "x") ) ) ); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json") ); try { var response = await client.GetAsync(endpoint); if (response.IsSuccessStatusCode) { using (var content = await response.Content.ReadAsStreamAsync()) { using (var reader = new System.IO.StreamReader(content)) { return await reader.ReadToEndAsync(); } } } else { Console.WriteLine($"Error: HTTP {response.StatusCode}"); return null; } } catch (HttpRequestException e) { Console.WriteLine($"Request error: {e.Message}"); return null; } } } ``` -------------------------------- ### Python Date Conversion Examples Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/types.md Demonstrates converting between string and datetime objects in Python, including handling ISO 8601 format. ```Python from datetime import datetime # String to date date_str = "20240115" date_obj = datetime.strptime(date_str, "%Y%m%d") # Date to string date_obj = datetime(2024, 1, 15) date_str = date_obj.strftime("%Y%m%d") # ISO datetime iso_str = "2024-01-15T15:30:00Z" datetime_obj = datetime.fromisoformat(iso_str.replace('Z', '+00:00')) ``` -------------------------------- ### GET /projects.json Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/endpoints.md Retrieve a list of all projects. Requires Basic Authentication. Returns a JSON array of project objects. ```APIDOC ## GET /projects.json ### Description Retrieve a list of all projects. ### Method GET ### Endpoint /projects.json ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **id** (integer) - Project ID - **name** (string) - Project name - **description** (string) - Project description - **status** (string) - Project status (active, archived) - **category-id** (integer) - Project category ID - **company-id** (integer) - Company ID - **start-date** (string) - Project start date (YYYYMMDD) - **end-date** (string) - Project end date (YYYYMMDD) - **privacy-enabled** (boolean) - Whether privacy is enabled - **reply-by-email-enabled** (boolean) - Whether email replies are enabled #### Response Example None ``` -------------------------------- ### Check cURL Installation Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/api-reference/php.md Verifies if the cURL extension is loaded in the PHP environment. This is a prerequisite for making API requests. ```php if (extension_loaded('curl')) { echo "cURL is installed"; } else { echo "cURL is NOT installed"; } ``` -------------------------------- ### Create Task using cURL Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/quickstart.md Example of how to create a new task in a to-do list using cURL. Includes setting the Content-Type and request body. ```bash # Create task curl -X POST https://mycompany.teamwork.com/todo_lists/5100/todo_items.json \ -u "your_api_key:xxx" \ -H "Content-Type: application/json" \ -d '{"todo-item":{"content":"Test task"}}' ``` -------------------------------- ### JavaScript/Node.js Date Conversion Examples Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/types.md Shows how to convert date strings to Date objects and vice versa in JavaScript, including parsing YYYYMMDD format. ```JavaScript // String to date const dateStr = "20240115"; const year = dateStr.substring(0, 4); const month = dateStr.substring(4, 6); const day = dateStr.substring(6, 8); const dateObj = new Date(`${year}-${month}-${day}`); // Date to string const dateObj = new Date("2024-01-15"); const dateStr = dateObj.toISOString().split('T')[0].replace(/-/g, ''); ``` -------------------------------- ### API Key Configuration Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/quickstart.md Provides instructions on how to securely configure your API key using environment variables or configuration files, with examples for Python, Node.js, and Go. ```APIDOC ## Configuration ### Environment Variables ```bash export TEAMWORK_COMPANY="mycompany" export TEAMWORK_API_KEY="your_api_key" ``` ### Configuration Files Create a `.env` file (do NOT commit to git): ``` TEAMWORK_COMPANY=mycompany TEAMWORK_API_KEY=your_api_key_here ``` ``` -------------------------------- ### Testing with cURL Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/quickstart.md Provides examples of how to use cURL to interact with the API for common operations like listing projects, creating tasks, updating projects, and deleting tasks. ```APIDOC ## Testing Your Integration ### Test with cURL ```bash # List projects curl -u "your_api_key:xxx" https://mycompany.teamwork.com/projects.json # Create task curl -X POST https://mycompany.teamwork.com/todo_lists/5100/todo_items.json \ -u "your_api_key:xxx" \ -H "Content-Type: application/json" \ -d '{"todo-item":{"content":"Test task"}}' # Update project curl -X PUT https://mycompany.teamwork.com/projects/12345.json \ -u "your_api_key:xxx" \ -H "Content-Type: application/json" \ -d '{"project":{"name":"New Name"}}' # Delete task curl -X DELETE https://mycompany.teamwork.com/tasks/67890.json \ -u "your_api_key:xxx" ``` ``` -------------------------------- ### Example: Authentication Error (401) Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/errors.md Illustrates the JSON response for a 401 Unauthorized error, typically due to an invalid API key. ```json { "error": { "message": "Invalid API key or authentication failed", "code": "UNAUTHORIZED", "details": "The API key provided is invalid or expired" } } ``` -------------------------------- ### Example: Invalid Parameter Error (400) Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/errors.md Shows the JSON response for a 400 Bad Request error, indicating a missing required parameter. ```json { "error": { "message": "Required parameter missing: 'content'", "code": "INVALID_REQUEST", "details": "The 'content' field is required when creating a task" } } ``` -------------------------------- ### SSL Verification in Go Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/configuration.md Explains that Go's default http.Client verifies SSL certificates and shows how to configure an insecure client for development/testing. ```Go // Default http.Client verifies certificates client := &http.Client{} // For development/testing only (insecure): // client.Transport = &http.Transport{ // TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // } ``` -------------------------------- ### HTTP Basic Authentication Example Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/quickstart.md Illustrates how to construct the Authorization header for HTTP Basic Authentication using an API key. This involves combining the key with 'xxx', Base64 encoding it, and formatting it as 'Basic {encodedString}'. ```text API Key: abc123 Password: xxx Combined: abc123:xxx Base64: YWJjMTIzOnh4eA== Header: Authorization: Basic YWJjMTIzOnh4eA== ``` -------------------------------- ### POST /projects.json Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/endpoints.md Create a new project with specified details. Requires Basic Authentication. Returns the created project object. ```APIDOC ## POST /projects.json ### Description Create a new project. ### Method POST ### Endpoint /projects.json ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (string) - Required - Project name - **description** (string) - Optional - Project description - **category-id** (integer) - Optional - Category ID for grouping - **company-id** (integer) - Required - Company ID - **start-date** (string) - Optional - Start date (YYYYMMDD) - **end-date** (string) - Optional - End date (YYYYMMDD) - **privacy-enabled** (boolean) - Optional - Enable privacy (default: false) ### Request Example ```json { "project": { "name": "Brand New Project", "description": "A demo project", "company-id": "123", "category-id": "0", "privacy-enabled": true, "start-date": "", "end-date": "" } } ``` ### Response #### Success Response (201) - **id** (integer) - Project ID - **name** (string) - Project name - **description** (string) - Project description - **status** (string) - Project status (active, archived) - **category-id** (integer) - Project category ID - **company-id** (integer) - Company ID - **start-date** (string) - Project start date (YYYYMMDD) - **end-date** (string) - Project end date (YYYYMMDD) - **privacy-enabled** (boolean) - Whether privacy is enabled - **reply-by-email-enabled** (boolean) - Whether email replies are enabled #### Response Example None ``` -------------------------------- ### Create and List Tasks with Python Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/api-reference/python.md This example demonstrates how to list projects and create a new task with a due date using the Teamwork API in Python. It includes functions for listing projects and creating tasks, along with main execution logic. ```python import urllib3 import json from datetime import datetime, timedelta def list_projects(company, api_key): """Get all projects""" http = urllib3.PoolManager() url = "https://{0}.teamwork.com/projects.json".format(company) headers = urllib3.util.make_headers(basic_auth=api_key + ":xxx") response = http.request('GET', url, headers=headers) return json.loads(response.data.decode('utf-8')) def create_task(company, api_key, list_id, task_content, due_date=None): """Create a new task""" http = urllib3.PoolManager() url = "https://{0}.teamwork.com/todo_lists/{1}/todo_items.json".format( company, list_id ) task_data = { "todo-item": { "content": task_content, "notify": True } } if due_date: task_data["todo-item"]["due-date"] = due_date headers = urllib3.util.make_headers(basic_auth=api_key + ":xxx") headers['Content-Type'] = 'application/json' body = json.dumps(task_data) response = http.request('POST', url, headers=headers, body=body) if response.status == 201: return json.loads(response.data.decode('utf-8')) else: raise Exception("Failed to create task") # Main execution if __name__ == "__main__": company = "mycompany" api_key = "your_api_key" task_list_id = "5100" # List projects print("Fetching projects...") projects = list_projects(company, api_key) print(json.dumps(projects, indent=2)) # Create task with due date tomorrow tomorrow = datetime.now() + timedelta(days=1) due_date = tomorrow.strftime("%Y%m%d") print("\nCreating task...") task = create_task( company, api_key, task_list_id, "Complete API integration", due_date ) print("Created task ID: {0}".format(task['todo-item']['id'])) ``` -------------------------------- ### Complete API Request Headers Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/configuration.md Demonstrates how to set up request headers for API calls in Python and PHP, including authentication and content type. ```Python import urllib3 http = urllib3.PoolManager() headers = urllib3.util.make_headers(basic_auth=key + ":xxx") headers['Accept'] = 'application/json' headers['Content-Type'] = 'application/json' request = http.request('GET', url, headers=headers) ``` ```PHP $headers = array( "Authorization: BASIC " . base64_encode($key . ":xxx"), "Accept: application/json", "Content-Type: application/json" ); curl_setopt($channel, CURLOPT_HTTPHEADER, $headers); ``` -------------------------------- ### Implement Basic GET Request Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/api-reference/php.md A function to perform a GET request to the Teamwork API. It handles authentication and returns the JSON response. ```php ``` -------------------------------- ### Basic GET Request Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/api-reference/python.md Make a GET request to the Teamwork API to retrieve data. This function handles authentication and JSON parsing. ```APIDOC ## GET Request ### Description Make a GET request to the Teamwork API to retrieve data. This function handles authentication and JSON parsing. ### Method GET ### Endpoint `https://{company}.teamwork.com/{endpoint}` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Retrieve all projects company = "mycompany" api_key = "your_api_key_here" try: projects = get_request(company, api_key, "projects.json") print(json.dumps(projects, indent=2)) except Exception as e: print("Error: {0}".format(e)) ``` ### Response #### Success Response (200) - **response_data** (dict) - Parsed JSON response #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Basic GET Request Implementation Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/api-reference/nodejs.md Implement a function to make a GET request to the Teamwork API. It handles authentication and parses the JSON response. ```javascript var request = require('request'); function getRequest(company, apiKey, action, callback) { /** * Make a GET request to the Teamwork API. * * @param {string} company - Company subdomain * @param {string} apiKey - API key for authentication * @param {string} action - API endpoint (e.g., "projects.json") * @param {Function} callback - Callback function(error, response, body) */ var base64 = new Buffer(apiKey + ":xxx").toString("base64"); var options = { hostname: company + ".teamworkpm.net", path: "/" + action, method: "GET", encoding: "utf8", headers: { "Authorization": "BASIC " + base64, "Content-Type": "application/json" } }; request(options, function(error, response, body) { if (!error && response.statusCode == 200) { var data = JSON.parse(body); callback(null, response.statusCode, data); } else { callback(error || "Status: " + response.statusCode, response.statusCode, body); } }); } ``` -------------------------------- ### Simpler GET Request Implementation Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/api-reference/nodejs.md A simplified version of the GET request function using the 'request' library directly. It constructs the URL and sets headers for JSON response. ```javascript // Or using request library directly (simpler): function getRequestSimple(company, apiKey, action, callback) { var url = "https://" + company + ".teamwork.com/" + action; var base64 = new Buffer(apiKey + ":xxx").toString("base64"); request({ url: url, method: "GET", headers: { "Authorization": "BASIC " + base64, "Accept": "application/json" }, json: true }, function(error, response, body) { callback(error, response ? response.statusCode : null, body); }); } ``` -------------------------------- ### Example Usage of POST Request Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/api-reference/python.md Demonstrates creating a new task item in a specific task list using the post_request function. The task data includes content, description, due date, and priority. ```python company = "mycompany" api_key = "your_api_key_here" task_list_id = "5100" task_data = { "todo-item": { "content": "Complete project documentation", "description": "Write comprehensive API docs", "due-date": "20240131", "priority": "high" } } try: response = post_request( company, api_key, "todo_lists/{0}/todo_items.json".format(task_list_id), task_data ) print("Task created: {0}".format(response)) except Exception as e: print("Error: {0}".format(e)) ``` -------------------------------- ### Implement GET Request to Teamwork API Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/api-reference/python.md This function makes a GET request to the Teamwork API. It handles authentication and JSON parsing. Use this to retrieve data from the API. ```python import urllib3 import json def get_request(company, api_key, endpoint): """ Make a GET request to the Teamwork API. Args: company (str): Company subdomain api_key (str): API key for authentication endpoint (str): API endpoint (e.g., "projects.json") Returns: dict: Parsed JSON response Raises: urllib3.exceptions.HTTPError: On network/HTTP errors """ http = urllib3.PoolManager() url = "https://{0}.teamwork.com/{1}".format(company, endpoint) headers = urllib3.util.make_headers(basic_auth=api_key + ":xxx") request = http.request('GET', url, headers=headers) if request.status == 200: response_data = json.loads(request.data.decode('utf-8')) return response_data else: raise Exception("API Error: {0}".format(request.status)) ``` -------------------------------- ### Basic GET Request Implementation in Java Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/api-reference/java.md Implements a method to perform a GET request to the Teamwork API. It handles URL construction, authentication via Basic Auth, and response retrieval. ```java import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Base64; public class TeamworkAPI { public static void main(String[] args) { String APIKey = "YOUR_API_KEY_HERE"; String TeamworkURL = "https://YOUR_COMPANY.teamwork.com"; String response = getRequest(TeamworkURL, "/projects.json", APIKey); System.out.println(response); } public static String getRequest(String teamworkURL, String action, String apiKey) { /** * Make a GET request to the Teamwork API. * * @param teamworkURL - Base Teamwork URL * @param action - API endpoint path (with leading /) * @param apiKey - API key for authentication * @return Response body as string */ HttpURLConnection connection = null; try { URL url = new URL(teamworkURL + action); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); // Set authorization header String userpassword = apiKey + ":xxx"; String encodedAuthorization = Base64.getEncoder() .encodeToString(userpassword.getBytes()); connection.setRequestProperty("Authorization", "Basic " + encodedAuthorization); connection.setRequestProperty("Accept", "application/json"); // Get response InputStream responseStream = connection.getInputStream(); String response = streamToString(responseStream); return response; } catch (Exception e) { System.out.println("Error: " + e.getMessage()); return null; } finally { if (connection != null) { connection.disconnect(); } } } public static String streamToString(InputStream in) throws java.io.IOException { /** * Convert InputStream to String. */ StringBuilder out = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line; while ((line = br.readLine()) != null) { out.append(line); } br.close(); return out.toString(); } } ``` -------------------------------- ### Fetch Data with Fetch API GET Request Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/api-reference/nodejs.md This snippet shows how to perform a GET request to the Teamwork API using the modern Fetch API. It handles JSON responses and basic error logging. ```javascript const company = "mycompany"; const apiKey = "your_api_key"; fetch(`https://${company}.teamwork.com/projects.json`, { method: 'GET', headers: { 'Authorization': 'Basic ' + btoa(apiKey + ':xxx'), 'Accept': 'application/json' } }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); ``` -------------------------------- ### Go Basic GET Request Implementation Source: https://github.com/teamwork/codesamples/blob/master/_autodocs/api-reference/go.md Implements a function to make a GET request to the Teamwork API, handling authentication, response parsing, and error logging. Requires the API key and endpoint path. ```go package main import ( "encoding/base64" "encoding/json" "io/ioutil" "log" "net/http" ) const ( siteName string = "{{yourSiteName}}" apiUrl string = "https://" + siteName + ".teamwork.com/" apiKey string = "{{yourApiKey}}" dataPreference string = "json" ) type ProjectJson struct { Project Project `json:"project"` } type Project struct { Category_id string `json:"category-id"` CompanyID string `json:"companyId"` Description string `json:"description"` EndDate string `json:"endDate"` Harvest_timers_enabled bool `json:"harvest-timers-enabled"` Name string `json:"name"` NewCompany string `json:"newCompany"` PrivacyEnabled bool `json:"privacyEnabled"` ReplyByEmailEnabled bool `json:"replyByEmailEnabled"` StartDate string `json:"startDate"` } func main() { getRequest("projects.json") } func getRequest(endPoint string) { /** * Make a GET request to the Teamwork API. * * @param endPoint - API endpoint path */ client := &http.Client{} req, err := http.NewRequest("GET", apiUrl+endPoint, nil) if err != nil { log.Fatal("Error creating request: ", err) } req.Header.Add("Authorization", "Basic "+basicAuth(apiKey)) req.Header.Add("Accept", "application/json") resp, err := client.Do(req) if err != nil { log.Fatal("Error making request: ", err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Fatal("Error reading response: ", err) } var p ProjectJson err = json.Unmarshal(body, &p) if err != nil { log.Fatal("Error parsing JSON: ", err) } log.Println("Project Name:", p.Project.Name) log.Println("Full Response:", string(body)) } func basicAuth(apiKey string) string { /** * Encode API key in base64 for Basic Authentication. * * @param apiKey - API key to encode * @return Base64 encoded "apiKey:xxx" */ return base64.StdEncoding.EncodeToString([]byte(apiKey + ":xxx")) } ```