How to extend the REST remote with custom endpoints - Example

Hi,

here’s some code I wrote that demonstrates how to extend the REST remote through background scripts.

In this example, we define a new endpoint GET /ext/filename?<externalid> that returns the filename of the database item with the specified External ID:

// Called when a request is made to the REST server
procedure OnRESTRequestRaw(Request: TRawRESTRequest; var Response: TRawRESTResponse);
var
  id: string;
  pi: IPlaylistItem;
begin
  if (Request.Method = 'GET') and (Request.Document = '/ext/filename') then begin
    id := Request.Parameters.GetValue('id');
    if id = '' then begin
      Response.ResponseNo := 400;
      Response.Data := 'ID not specified';
      Response.Handled := true;
      exit;
    end;

    pi := IDBConnection(Database(0)).CreatePlaylistItemEx(id, true);
    if pi = nil then begin
      Response.ResponseNo := 404;
      Response.Data := 'Item with specified ID was not found';
      Response.Handled := true;
      exit;
    end;

    if not pi.IsFile then begin
      Response.ResponseNo := 404;
      Response.Data := 'Item with specified ID was found but is not a file';
      Response.Handled := true;
      exit;
    end;

    Response.ResponseNo := 200;
    Response.Data := pi.AsFile.GetFilename;
    Response.Handled := true;

  end;
end;

Testing with cURL:

$ curl -s http://xxx:xxx@127.0.0.1:9300/ext/filename?id=1234
M:\Music\a-ha\Hunting High and Low\06 The Sun Always Shines On Tv.mp3
1 Like

Relevant type definitions:

  TRawRESTRequest = record
    Method: string;
    Document: string;
    Parameters: IStrings;
  end;

  TRawRESTResponse = record
    ResponseNo: integer;
    ContentType: string;
    CharSet: string;
    Data: string;
    Handled: boolean;
  end;