### Run the Go Quickstart Sample Source: https://developers.google.com/workspace/tasks/quickstart/go Build and execute the Go quickstart application. This command initiates the application, which will then prompt for authorization on the first run. ```bash go run quickstart.go ``` -------------------------------- ### Install http-server Package Source: https://developers.google.com/workspace/tasks/quickstart/js Install the http-server package using npm. This is a prerequisite for running the local web server. ```bash npm install http-server ``` -------------------------------- ### Install Google Client Library for Python Source: https://developers.google.com/workspace/tasks/quickstart/python Install the necessary Google client libraries for Python to interact with Google APIs. Ensure you have Python 3.10.7 or greater and pip installed. ```bash python3 -m pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib ``` -------------------------------- ### Start Local Web Server Source: https://developers.google.com/workspace/tasks/quickstart/js Start a local web server on port 8000 using npx. This server will host your JavaScript application. ```bash npx http-server -p 8000 ``` -------------------------------- ### Install Node.js Client Libraries Source: https://developers.google.com/workspace/tasks/quickstart/nodejs Install the necessary Google API client libraries for Node.js using npm. This includes the main googleapis library and the local-auth library for authentication. ```bash npm install googleapis@105 @google-cloud/local-auth@2.1.0 --save ``` -------------------------------- ### Read-Modify-Write Cycle with PATCH Source: https://developers.google.com/workspace/tasks/performance This example demonstrates a read-modify-write cycle using a GET request to retrieve a partial resource, followed by a PATCH request to update specific fields. It highlights the use of the `fields` parameter and the `If-Match` header for ETag-based updates. ```APIDOC ## GET https://www.googleapis.com/demo/v1/324?fields=etag,title,comment,characteristics ### Description Retrieves a partial representation of a resource, including its ETag, title, comment, and characteristics. ### Method GET ### Endpoint https://www.googleapis.com/demo/v1/324 ### Query Parameters - **fields** (string) - Optional - Specifies the fields to return in the response. ### Response #### Success Response (200) - **etag** (string) - The ETag of the resource. - **title** (string) - The title of the resource. - **comment** (string) - The comment associated with the resource. - **characteristics** (object) - An object containing various characteristics of the resource. - **length** (string) - **level** (string) - **followers** (array of strings) ### Response Example ```json { "etag": "ETagString", "title": "New title", "comment": "First comment.", "characteristics": { "length": "short", "level": "5", "followers": ["Jo", "Will"] } } ``` ## PATCH https://www.googleapis.com/demo/v1/324?fields=etag,title,comment,characteristics ### Description Updates a resource using a partial representation. This example modifies the title, comment, and characteristics, demonstrating how to clear values, delete fields, modify existing fields, and add new ones. It requires the `If-Match` header with the current ETag. ### Method PATCH ### Endpoint https://www.googleapis.com/demo/v1/324 ### Query Parameters - **fields** (string) - Optional - Specifies the fields to return in the response. ### Headers - **Authorization** (string) - Required - Bearer token for authentication. - **Content-Type** (string) - Required - `application/json`. - **If-Match** (string) - Required - The current ETag of the resource (e.g., `"ETagString"`). ### Request Body - **etag** (string) - The ETag of the resource. - **title** (string) - The new title. Setting to an empty string clears the value. - **comment** (null) - Setting to null deletes the comment field. - **characteristics** (object) - An object containing characteristics to update or add. - **length** (string) - **level** (string) - Modified value. - **followers** (array of strings) - Replaced array. - **accuracy** (string) - New characteristic to add. ### Request Example ```json { "etag": "ETagString", "title": "", "comment": null, "characteristics": { "length": "short", "level": "10", "followers": ["Jo", "Liz"], "accuracy": "high" } } ``` ### Response #### Success Response (200) - **etag** (string) - The new ETag of the resource. - **title** (string) - The updated title. - **characteristics** (object) - The updated characteristics object. - **length** (string) - **level** (string) - **followers** (array of strings) - **accuracy** (string) ### Response Example ```json { "etag": "newETagString", "title": "", "characteristics": { "length": "short", "level": "10", "followers": ["Jo", "Liz"], "accuracy": "high" } } ``` ``` -------------------------------- ### Partial Resource Response Example Source: https://developers.google.com/workspace/tasks/performance This example shows a partial response after applying the 'fields' parameter, containing only the specified 'kind' and 'title'/'length' from the 'items'. ```json { "kind": "demo", "items": [{ "title": "First title", "characteristics": { "length": "short" } }, { "title": "Second title", "characteristics": { "length": "long" } }, ... ] } ``` -------------------------------- ### Full Resource Response Example Source: https://developers.google.com/workspace/tasks/performance This is an example of a full resource response from a generic API, illustrating the data structure before applying field filtering. ```json { "kind": "demo", ... "items": [ { "title": "First title", "comment": "First comment.", "characteristics": { "length": "short", "accuracy": "high", "followers": ["Jo", "Will"], }, "status": "active", ... }, { "title": "Second title", "comment": "Second comment.", "characteristics": { "length": "long", "accuracy": "medium" "followers": [ ], }, "status": "pending", ... }, ... ] } ``` -------------------------------- ### Configure build.gradle for Google Tasks API Source: https://developers.google.com/workspace/tasks/quickstart/java Defines project settings, repositories, and dependencies required for the Google Tasks API Java quickstart. ```gradle apply plugin: 'java' apply plugin: 'application' mainClassName = 'TasksQuickstart' sourceCompatibility = 11 targetCompatibility = 11 version = '1.0' repositories { mavenCentral() } dependencies { implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-tasks:v1-rev20210709-2.0.0' } ``` -------------------------------- ### Java Quickstart for Google Tasks API Source: https://developers.google.com/workspace/tasks/quickstart/java This Java code authenticates with the Google Tasks API and lists the first 10 task lists. Ensure you have a 'credentials.json' file in the resources directory and have configured the necessary scopes. ```java import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp; import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.gson.GsonFactory; import com.google.api.client.util.store.FileDataStoreFactory; import com.google.api.services.tasks.Tasks; import com.google.api.services.tasks.TasksScopes; import com.google.api.services.tasks.model.TaskList; import com.google.api.services.tasks.model.TaskLists; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.security.GeneralSecurityException; import java.util.Collections; import java.util.List; public class TasksQuickstart { private static final String APPLICATION_NAME = "Google Tasks API Java Quickstart"; private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); private static final String TOKENS_DIRECTORY_PATH = "tokens"; /** * Global instance of the scopes required by this quickstart. * If modifying these scopes, delete your previously saved tokens/ folder. */ private static final List SCOPES = Collections.singletonList(TasksScopes.TASKS_READONLY); private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; /** * Creates an authorized Credential object. * * @param HTTP_TRANSPORT The network HTTP Transport. * @return An authorized Credential object. * @throws IOException If the credentials.json file cannot be found. */ private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException { // Load client secrets. InputStream in = TasksQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH); if (in == null) { throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH); } GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in)); // Build flow and trigger user authorization request. GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES) .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH))) .setAccessType("offline") .build(); LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build(); return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user"); } public static void main(String... args) throws IOException, GeneralSecurityException { // Build a new authorized API client service. final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); Tasks service = new Tasks.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) .setApplicationName(APPLICATION_NAME) .build(); // Print the first 10 task lists. TaskLists result = service.tasklists().list() .setMaxResults(10) .execute(); List taskLists = result.getItems(); if (taskLists == null || taskLists.isEmpty()) { System.out.println("No task lists found."); } else { System.out.println("Task lists:"); for (TaskList tasklist : taskLists) { System.out.printf("%s (%s)\n", tasklist.getTitle(), tasklist.getId()); } } } } ``` -------------------------------- ### Partial Response Example Source: https://developers.google.com/workspace/tasks/performance Demonstrates how to use the `fields` query parameter to retrieve only specific fields from a response, reducing data transfer. ```APIDOC ## GET /demo/v1 ### Description Retrieves a resource, allowing for partial responses using the `fields` query parameter. ### Method GET ### Endpoint https://www.googleapis.com/demo/v1 ### Query Parameters - **fields** (string) - Optional - Specifies which fields to return in the response. ### Response #### Success Response (200 OK) Returns the requested data, with only the fields specified in the `fields` parameter. #### Response Example ```json { "kind": "demo", "items": [ { "title": "First title", "characteristics": { "length": "short" } }, { "title": "Second title", "characteristics": { "length": "long" } }, ... ] } ``` #### Error Response (400 Bad Request) Returned if the `fields` query parameter is invalid. #### Error Response Example ``` "Invalid field selection a/b" ``` ``` -------------------------------- ### Get Google Tasks API and OAuth2.0 packages in Go Source: https://developers.google.com/workspace/tasks/quickstart/go Download the necessary Google Tasks API client library and the OAuth2.0 package for your Go project. These are required to authenticate and interact with the API. ```bash go get google.golang.org/api/tasks/v1 go get golang.org/x/oauth2/google ``` -------------------------------- ### Handling PATCH Request When PATCH Verb is Not Supported Source: https://developers.google.com/workspace/tasks/performance This example demonstrates how to use an HTTP POST request with an `X-HTTP-Method-Override` header to simulate a PATCH request when the PATCH verb is blocked by a firewall. ```APIDOC ## POST https://www.googleapis.com/... ### Description Simulates a PATCH request using an HTTP POST request when the PATCH verb is not supported. This is achieved by setting the `X-HTTP-Method-Override` header to `PATCH`. ### Method POST ### Endpoint https://www.googleapis.com/... ### Headers - **X-HTTP-Method-Override** (string) - Required - Set to `PATCH` to override the POST method. ### Request Body [The request body would typically be the same as a standard PATCH request body.] ### Request Example ```http POST https://www.googleapis.com/... Authorization: Bearer your_auth_token Content-Type: application/json X-HTTP-Method-Override: PATCH { "field": "value" } ``` ``` -------------------------------- ### List and Add Tasks using Tasks API Source: https://developers.google.com/workspace/tasks/oauth-and-tasks-on-android Examples for retrieving all task lists, fetching tasks from the default list, and inserting a new task with a title, notes, and due date. Ensure your AndroidManifest.xml includes the INTERNET permission. ```java List taskLists = service.tasklists.list().execute().items; ``` ```java List tasks = service.tasks.list("@default").execute().items; ``` ```java Task task = new Task(); task.title = "New Task"; task.notes = "Please complete me"; task.due = "2010-10-15T12:00:00.000Z"; Task result = service.tasks.insert("@default", task).execute(); ``` -------------------------------- ### Get Google Accounts using GoogleAccountManager Source: https://developers.google.com/workspace/tasks/oauth-and-tasks-on-android Use GoogleAccountManager for a simpler way to get only Google accounts. Requires the activity context. ```java GoogleAccountManager googleAccountManager = new GoogleAccountManager(activity); Account[] accounts = googleAccountManager.getAccounts(); ``` -------------------------------- ### Retrieve partial resource for modification (GET) Source: https://developers.google.com/workspace/tasks/performance Use GET with the `fields` parameter to retrieve only the necessary data for modification. This is crucial for resources using ETags. ```http GET https://www.googleapis.com/demo/v1/324**?fields=etag,title,comment,characteristics** Authorization: Bearer your_auth_token ``` -------------------------------- ### Get a Task List Source: https://developers.google.com/workspace/tasks/reference/rest/v1/tasklists Returns the authenticated user's specified task list. ```APIDOC ## GET /tasks/v1/users/@me/lists/{tasklist} ### Description Returns the authenticated user's specified task list. ### Method GET ### Endpoint /tasks/v1/users/@me/lists/{tasklist} ### Parameters #### Path Parameters - **tasklist** (string) - Required - The ID of the task list to get. ``` -------------------------------- ### Get Task Source: https://developers.google.com/workspace/tasks/reference/rest/v1/tasks Returns the specified task. ```APIDOC ## get ### Description Returns the specified task. ### Method (HTTP method not specified in source) ### Endpoint (Endpoint not specified in source) ``` -------------------------------- ### Move a Task in Google Tasks (.NET) Source: https://developers.google.com/workspace/tasks/order This C# code example demonstrates moving a task in Google Tasks. The `Fetch()` method executes the move operation and returns a Task object containing the updated parent and position. ```C# Task result = service.Tasks.Move("@default", "taskID", parent: "parentTaskID", previous: "previousTaskID").Fetch(); // Print the new values. Console.WriteLine(result.Parent); Console.WriteLine(result.Position); ``` -------------------------------- ### Constructing a Patch Request Directly Source: https://developers.google.com/workspace/tasks/performance This example shows how to construct a PATCH request directly without first retrieving the existing data. It's useful for updating fields to new values or adding new fields, and demonstrates how to overwrite existing values or create new ones. ```APIDOC ## PATCH https://www.googleapis.com/demo/v1/324?fields=comment,characteristics ### Description Constructs a PATCH request directly to update or add fields without a preceding GET request. This example updates the 'comment' field and modifies 'characteristics', including overwriting existing values, creating new ones, and removing a field. ### Method PATCH ### Endpoint https://www.googleapis.com/demo/v1/324 ### Query Parameters - **fields** (string) - Optional - Specifies the fields to return in the response. ### Headers - **Authorization** (string) - Required - Bearer token for authentication. - **Content-Type** (string) - Required - `application/json`. ### Request Body - **comment** (string) - The new comment value. Overwrites if exists, otherwise sets the value. - **characteristics** (object) - An object containing characteristics to update or add. - **volume** (string) - Overwrites if exists, otherwise creates the characteristic. - **accuracy** (null) - Setting to null removes the field if it exists. ### Request Example ```json { "comment": "A new comment", "characteristics": { "volume": "loud", "accuracy": null } } ``` ``` -------------------------------- ### Patch (Partial Update) Example Source: https://developers.google.com/workspace/tasks/performance Illustrates how to use the HTTP `PATCH` verb to update only specific fields of a resource, minimizing the data sent in the request. ```APIDOC ## PATCH /demo/v1/{resourceId} ### Description Updates specific fields of a resource using the HTTP `PATCH` verb. Only the fields provided in the request body are modified. ### Method PATCH ### Endpoint https://www.googleapis.com/demo/v1/{resourceId} ### Parameters #### Path Parameters - **resourceId** (string) - Required - The ID of the resource to update. #### Request Body - **title** (string) - Required - The new title for the resource. ### Request Example ```json { "title": "New title" } ``` ### Response #### Success Response (200 OK) Returns the full representation of the updated resource. #### Response Example ```json { "title": "New title", "comment": "First comment.", "characteristics": { "length": "short", "accuracy": "high", "followers": ["Jo", "Will"] }, "status": "active", ... } ``` ``` -------------------------------- ### Initialize Gradle Project Source: https://developers.google.com/workspace/tasks/quickstart/java Sets up a basic Gradle project structure and initializes it for Java development. ```bash gradle init --type basic mkdir -p src/main/java src/main/resources ``` -------------------------------- ### Change to the working directory in Go Source: https://developers.google.com/workspace/tasks/quickstart/go Navigate into the newly created project directory to begin setting up your Go application. ```bash cd quickstart ``` -------------------------------- ### Simple HTTP GET Request Source: https://developers.google.com/workspace/tasks/performance A basic HTTP GET request to a generic API without any parameters for retrieving a full resource. ```http https://www.googleapis.com/demo/v1 ``` -------------------------------- ### Run the Java Sample Source: https://developers.google.com/workspace/tasks/quickstart/java Execute this command in your terminal to run the Java sample. The first time, it will prompt for authorization. ```bash gradle run ``` -------------------------------- ### Run Node.js Sample Source: https://developers.google.com/workspace/tasks/quickstart/nodejs Execute the Node.js sample application from your working directory to interact with the Google Tasks API. The first run will prompt for authorization. ```bash node . ``` -------------------------------- ### Create a working directory in Go Source: https://developers.google.com/workspace/tasks/quickstart/go Use this command to create a new directory for your project. Ensure you are in the desired parent directory. ```bash mkdir quickstart ``` -------------------------------- ### Initialize a new Go module Source: https://developers.google.com/workspace/tasks/quickstart/go Initialize a new Go module within your project directory. This command creates a go.mod file to manage dependencies. ```bash go mod init quickstart ``` -------------------------------- ### Get Google Accounts using AccountManager Source: https://developers.google.com/workspace/tasks/oauth-and-tasks-on-android Retrieve an array of Google accounts registered on the device using the AccountManager. Requires the activity context. ```java AccountManager accountManager = AccountManager.get(activity); Account[] accounts = accountManager.getAccountsByType("com.google"); ``` -------------------------------- ### Deleting a Field using PATCH Source: https://developers.google.com/workspace/tasks/performance To delete a field using a patch request, set the field's value to `null`. This example demonstrates deleting the 'comment' field. ```JSON "comment": null ``` -------------------------------- ### Task Creation and Ordering Parameters Source: https://developers.google.com/workspace/tasks/params Parameters used for creating and ordering tasks. ```APIDOC ## Creating a Task ### Parameters #### Query Parameters - **parent** (string) - Optional - Specify the task's parent task ID. No parameter indicates an insertion or a move to the top level of the task list. - **previous** (string) - Optional - Specify the task's previous task ID. No parameter indicates an insertion or a move to the first position in the sublist. ``` ```APIDOC ## Ordering a Task ### Parameters #### Query Parameters - **parent** (string) - Optional - Specify the task's parent task ID. No parameter indicates an insertion or a move to the top level of the task list. - **previous** (string) - Optional - Specify the task's previous task ID. No parameter indicates an insertion or a move to the first position in the sublist. ``` -------------------------------- ### Performing a Partial Update with PATCH Source: https://developers.google.com/workspace/tasks/performance Use the HTTP `PATCH` verb to update only specific fields of a resource, minimizing the data sent in the request. This example shows updating only the 'title' field of a resource. ```HTTP **PATCH https://www.googleapis.com/demo/v1/324** Authorization: Bearer your_auth_token Content-Type: application/json { **"title": "New title"** } ``` -------------------------------- ### Get OAuth 2.0 Access Token for Tasks API Source: https://developers.google.com/workspace/tasks/oauth-and-tasks-on-android Use AccountManager.getAuthToken() to request an access token for the Tasks API. Handle the result in a callback, checking for the token or exceptions like user denial. ```java manager.getAuthToken(account, AUTH_TOKEN_TYPE, null, activity, new AccountManagerCallback() { public void run(AccountManagerFuture future) { try { // If the user has authorized your application to use the tasks API // a token is available. String token = future.getResult().getString(AccountManager.KEY_AUTHTOKEN); // Now you can use the Tasks API... useTasksAPI(token); } catch (OperationCanceledException e) { // TODO: The user has denied you access to the API, you should handle that } catch (Exception e) { handleException(e); } } }, null); ``` -------------------------------- ### Set up Tasks API Service Object Source: https://developers.google.com/workspace/tasks/oauth-and-tasks-on-android Configure the Tasks API service by providing an access token, HTTP transport, and an API key obtained from the Google APIs Console. ```java useTasksAPI(String accessToken) { // Setting up the Tasks API Service HttpTransport transport = AndroidHttp.newCompatibleTransport(); AccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(accessToken); Tasks service = new Tasks(transport, accessProtectedResource, new JacksonFactory()); service.accessKey = INSERT_YOUR_API_KEY; service.setApplicationName("Google-TasksSample/1.0"); // TODO: now use the service to query the Tasks API } ``` -------------------------------- ### tasks.get Source: https://developers.google.com/workspace/tasks/reference/rest/v1/tasks/get Returns the specified task. Stay organized with collections. Save and categorize content based on your preferences. ```APIDOC ## GET /tasks/v1/lists/{tasklist}/tasks/{task} ### Description Returns the specified task. ### Method GET ### Endpoint `https://tasks.googleapis.com/tasks/v1/lists/{tasklist}/tasks/{task}` ### Parameters #### Path Parameters - **tasklist** (string) - Required - Task list identifier. - **task** (string) - Required - Task identifier. ### Request Body The request body must be empty. ### Response #### Success Response (200) If successful, the response body contains an instance of `Task`. ### Authorization scopes Requires one of the following OAuth scopes: - `https://www.googleapis.com/auth/tasks` - `https://www.googleapis.com/auth/tasks.readonly` ``` -------------------------------- ### Create a Task List Source: https://developers.google.com/workspace/tasks/reference/rest/v1/tasklists Creates a new task list and adds it to the authenticated user's task lists. ```APIDOC ## POST /tasks/v1/users/@me/lists ### Description Creates a new task list and adds it to the authenticated user's task lists. ### Method POST ### Endpoint /tasks/v1/users/@me/lists ### Request Body - **title** (string) - Required - The title of the new task list. Maximum length: 1024 characters. ``` -------------------------------- ### Run the Python Google Tasks API Sample Source: https://developers.google.com/workspace/tasks/quickstart/python Execute the Python script from your terminal to interact with the Google Tasks API. The first run will prompt for authorization. ```bash python3 quickstart.py ``` -------------------------------- ### tasklists.insert Source: https://developers.google.com/workspace/tasks/reference/rest/v1/tasklists/insert Creates a new task list and adds it to the authenticated user's task lists. A user can have up to 2000 lists at a time. ```APIDOC ## tasklists.insert ### Description Creates a new task list and adds it to the authenticated user's task lists. A user can have up to 2000 lists at a time. ### Method POST ### Endpoint https://tasks.googleapis.com/tasks/v1/users/@me/lists ### Request Body The request body contains an instance of `TaskList`. ### Response Body If successful, the response body contains a newly created instance of `TaskList`. ### Authorization Scopes Requires the following OAuth scope: - https://www.googleapis.com/auth/tasks ``` -------------------------------- ### Initialize Google Tasks API Client Source: https://developers.google.com/workspace/tasks/quickstart/js This HTML and JavaScript code sets up the basic structure for a web application that interacts with the Google Tasks API. It includes placeholders for your client ID and API key, and defines functions for authentication and fetching data. Ensure you replace '' and '' with your actual credentials. ```html Tasks API Quickstart

Tasks API Quickstart



    
    

```

--------------------------------

### List Google Tasks with Node.js

Source: https://developers.google.com/workspace/tasks/quickstart/nodejs

This Node.js script authenticates with Google, creates a Tasks API client, and lists the user's first 10 task lists. Ensure you have a `credentials.json` file in your working directory for authentication.

```javascript
import path from 'node:path';
import process from 'node:process';
import {authenticate} from '@google-cloud/local-auth';
import {google} from 'googleapis';

// The scope for reading tasks.
const SCOPES = ['https://www.googleapis.com/auth/tasks.readonly'];
// The path to the credentials file.
const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json');

/**
 * Lists the user's first 10 task lists.
 */
async function listTaskLists() {
  // Authenticate with Google and get an authorized client.
  const auth = await authenticate({
    scopes: SCOPES,
    keyfilePath: CREDENTIALS_PATH,
  });

  // Create a new Tasks API client.
  const service = google.tasks({version: 'v1', auth});
  // Get the list of task lists.
  const result = await service.tasklists.list({
    maxResults: 10,
  });
  const taskLists = result.data.items;
  if (taskLists?.length) {
    console.log('Task lists:');
    // Print the title and ID of each task list.
    taskLists.forEach((taskList) => {
      console.log(`${taskList.title} (${taskList.id})`);
    });
  } else {
    console.log('No task lists found.');
  }
}

await listTaskLists();

```

--------------------------------

### tasklists.get

Source: https://developers.google.com/workspace/tasks/reference/rest/v1/tasklists/get

Returns the authenticated user's specified task list. Stay organized with collections by saving and categorizing content based on your preferences.

```APIDOC
## GET https://tasks.googleapis.com/tasks/v1/users/@me/lists/{tasklist}

### Description
Returns the authenticated user's specified task list.

### Method
GET

### Endpoint
`https://tasks.googleapis.com/tasks/v1/users/@me/lists/{tasklist}`

### Parameters
#### Path Parameters
- **tasklist** (string) - Required - Task list identifier.

### Response Body
If successful, the response body contains an instance of `TaskList`.
```

--------------------------------

### Initialize Google Tasks API Client in Go

Source: https://developers.google.com/workspace/tasks/quickstart/go

This Go code initializes the Google Tasks API client. It handles authentication using OAuth2 by reading credentials from 'credentials.json' and storing tokens in 'token.json'. Use this to set up API access for your application.

```go
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"

	"golang.org/x/oauth2"
	"golang.org/x/oauth2/google"
	"google.golang.org/api/option"
	"google.golang.org/api/tasks/v1"
)

// Retrieve a token, saves the token, then returns the generated client.
func getClient(config *oauth2.Config) *http.Client {
	// The file token.json stores the user's access and refresh tokens, and is
	// created automatically when the authorization flow completes for the first
	// time.
	tokFile := "token.json"
	tok, err := tokenFromFile(tokFile)
	if err != nil {
		tok = getTokenFromWeb(config)
		saveToken(tokFile, tok)
	}
	return config.Client(context.Background(), tok)
}

// Request a token from the web, then returns the retrieved token.
func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {
	authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
	fmt.Printf("Go to the following link in your browser then type the " +
		"authorization code: \n%v\n", authURL)

	var authCode string
	if _, err := fmt.Scan(&authCode); err != nil {
		log.Fatalf("Unable to read authorization code: %v", err)
	}

	tok, err := config.Exchange(context.TODO(), authCode)
	if err != nil {
		log.Fatalf("Unable to retrieve token from web: %v", err)
	}
	return tok
}

// Retrieves a token from a local file.
func tokenFromFile(file string) (*oauth2.Token, error) {
	f, err := os.Open(file)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	tok := &oauth2.Token{}
	err = json.NewDecoder(f).Decode(tok)
	return tok, err
}

// Saves a token to a file path.
func saveToken(path string, token *oauth2.Token) {
	fmt.Printf("Saving credential file to: %s\n", path)
	f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
	if err != nil {
		log.Fatalf("Unable to cache oauth token: %v", err)
	}
	defer f.Close()
	json.NewEncoder(f).Encode(token)
}

func main() {
	ctx := context.Background()
	b, err := os.ReadFile("credentials.json")
	if err != nil {
		log.Fatalf("Unable to read client secret file: %v", err)
	}

	// If modifying these scopes, delete your previously saved token.json.
	config, err := google.ConfigFromJSON(b, tasks.TasksReadonlyScope)
	if err != nil {
		log.Fatalf("Unable to parse client secret file to config: %v", err)
	}
	client := getClient(config)

	srv, err := tasks.NewService(ctx, option.WithHTTPClient(client))
	if err != nil {
		log.Fatalf("Unable to retrieve tasks Client %v", err)
	}

	r, err := srv.Tasklists.List().MaxResults(10).Do()
	if err != nil {
		log.Fatalf("Unable to retrieve task lists. %v", err)
	}

	fmt.Println("Task Lists:")
	if len(r.Items) > 0 {
		for _, i := range r.Items {
			fmt.Printf("%s (%s)\n", i.Title, i.Id)
		}
	} else {
		fmt.Print("No task lists found.")
	}
}

```

--------------------------------

### Declare Servlet Mappings in web.xml

Source: https://developers.google.com/workspace/tasks/oauth-authorization-callback-handler

Defines servlet mappings for the application's entry point and the OAuth 2.0 callback handler.

```xml



 
   PrintTasksTitles
   com.google.oauthsample.PrintTasksTitlesServlet
 

 
   PrintTasksTitles
   /
 

 
   OAuthCodeCallbackHandlerServlet
   com.google.oauthsample.OAuthCodeCallbackHandlerServlet
 

 
   OAuthCodeCallbackHandlerServlet
   /oauth2callback
 


```

--------------------------------

### Insert Task

Source: https://developers.google.com/workspace/tasks/reference/rest/v1/tasks

Creates a new task on the specified task list.

```APIDOC
## insert

### Description
Creates a new task on the specified task list.

### Method
(HTTP method not specified in source)

### Endpoint
(Endpoint not specified in source)
```

--------------------------------

### Enable Gzip Compression for API Requests

Source: https://developers.google.com/workspace/tasks/performance

To reduce bandwidth, set the 'Accept-Encoding' header to 'gzip' and include 'gzip' in your User-Agent string. This requires additional CPU time for decompression.

```http
Accept-Encoding: gzip
User-Agent: my program (gzip)
```

--------------------------------

### Create Account Chooser Dialog

Source: https://developers.google.com/workspace/tasks/oauth-and-tasks-on-android

Build an AlertDialog to let the user select a Google account when multiple accounts are available. This code should be placed within the onCreateDialog method of your Activity.

```java
@Override
protected Dialog onCreateDialog(int id) {
  switch (id) {
    case DIALOG_ACCOUNTS:
      AlertDialog.Builder builder = new AlertDialog.Builder(this);
      builder.setTitle("Select a Google account");
      final Account[] accounts = accountManager.getAccountsByType("com.google");
      final int size = accounts.length;
      String[] names = new String[size];
      for (int i = 0; i < size; i++) {
        names[i] = accounts[i].name;
      }
      builder.setItems(names, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
          // Stuff to do when the account is selected by the user
          gotAccount(accounts[which]);
        }
      });
      return builder.create();
  }
  return null;
}
```

--------------------------------

### Override PATCH with POST

Source: https://developers.google.com/workspace/tasks/performance

If your firewall blocks PATCH requests, use a POST request with the `X-HTTP-Method-Override` header set to `PATCH`.

```http
POST https://www.googleapis.com/...
X-HTTP-Method-Override: PATCH
...
```