Sample code for 30+ languages & platforms
Pascal (Lazarus/Delphi)

Create a New GMail Label

See more GMail REST API Examples

Demonstrates how to create a new GMail label.

Chilkat Pascal (Lazarus/Delphi) Downloads

Pascal (Lazarus/Delphi)
program ChilkatDemo;

// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}

uses
  {$IFDEF UNIX}
  cthreads,
  {$ENDIF}
  SysUtils,
  CkDllLoader,
  Chilkat.Http,
  Chilkat.HttpResponse,
  Chilkat.JsonObject;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  success: Boolean;
  http: THttp;
  userId: string;
  json: TJsonObject;
  url: string;
  resp: THttpResponse;

begin
  success := False;

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

  http := THttp.Create;
  http.AuthToken := 'GMAIL-ACCESS-TOKEN';

  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".
  json := TJsonObject.Create;
  json.UpdateString('name','questions');
  json.UpdateString('labelListVisibility','labelShow');
  json.UpdateString('messageListVisibility','show');

  json.EmitCompact := False;
  WriteLn(json.Emit());

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

  url := 'https://www.googleapis.com/gmail/v1/users/{$userId}/labels';
  resp := THttpResponse.Create;
  success := http.HttpJson('POST',url,json,'application/json',resp);
  if (success = False) then
    begin
      WriteLn(http.LastErrorText);
      Exit;
    end;

  WriteLn('status = ' + resp.StatusCode);

  //  A 200 response status indicate success.
  if (resp.StatusCode <> 200) then
    begin
      WriteLn(resp.BodyStr);
      WriteLn('Failed.');
      Exit;
    end;

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

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

  WriteLn('response body:');
  WriteLn(resp.BodyStr);

  WriteLn('GMail label created!');


  http.Free;
  json.Free;
  resp.Free;

end;

// ---------------------------------------------------------------------------

begin

  try
    RunDemo;
  except
    on E: Exception do
      WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
  end;

  WriteLn;
  {$IFDEF MSWINDOWS}
  WriteLn('Press Enter to exit...');
  ReadLn;
  {$ENDIF}
end.