Sample code for 30+ languages & platforms
Dart

Create a New GMail Label

See more GMail REST API Examples

Demonstrates how to create a new GMail label.

Chilkat Dart Downloads

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  // This example requires the Chilkat API to have been previously unlocked.
  // See Global Unlock Sample for sample code.

  final http = CkHttp();
  http.authToken = 'GMAIL-ACCESS-TOKEN';

  final userId = 'me';
  http.setUrlVar('userId', userId);

  // Create the JSON to be sent in the HTTP request body.
  // The name of the new label is "questions".
  final json = CkJsonObject();
  json.updateString('name', 'questions');
  json.updateString('labelListVisibility', 'labelShow');
  json.updateString('messageListVisibility', 'show');

  json.emitCompact = false;
  print(json.emit());

  // The JSON contains this:
  // {
  //   "name": "questions",
  //   "labelListVisibility": "labelShow",
  //   "messageListVisibility": "show"
  // }

  final url = 'https://www.googleapis.com/gmail/v1/users/{\$userId}/labels';
  final resp = CkHttpResponse();
  try {
    http.httpJson('POST', url, json, 'application/json', resp);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  print('status = ${resp.statusCode}');

  // A 200 response status indicate success.
  if (resp.statusCode != 200) {
    print(resp.bodyStr);
    print('Failed.');
    return;
  }

  // A successful repsonse contains JSON that looks like this:

  // {
  //  "id": "Label_43",
  //  "name": "questions",
  //  "messageListVisibility": "show",
  //  "labelListVisibility": "labelShow"
  // }

  print('response body:');
  print(resp.bodyStr);

  print('GMail label created!');
}