使用Graph.cool API的Delphi?

时间:2017-10-18 23:38:38

标签: delphi facebook-graph-api graphql graphcool

如何使用Delphi连接Graph.cool?

我想构建一个Win32 / Win64 / OSX客户端

https://Graph.cool/有一个GraphQL(REST)API端点。

实施例: https://api.graph.cool/simple/v1/ENDPOINT

使用FaceBook GraphQL实现GraphQL的一个已知示例位于: http://docwiki.embarcadero.com/RADStudio/Tokyo/en/REST_Client_Library

我有一个示例查询:

mutation {
  createUser(
    authProvider: { 
      email: { email: "hello@hello.com", password: "hello" 
      }}
  )
  {
    id
  }
}

创建用户帐户。

我尝试使用TRestClient,但似乎无法放置非结构化字符串查询。

来自DFM的Snipplet:

var
  RESTRequest1: TRESTRequest;
  RESTRequest1 := TRESTRequest.Create(Self);
  RESTRequest1.Name := 'RESTRequest1';
  RESTRequest1.AcceptEncoding := ' ';
  RESTRequest1.Client := RESTClient1;
  RESTRequest1.Method := rmPOST;
  with RESTRequest1.Params.Add do begin 
    name := 'query';
    Options := [poAutoCreated];
    Value := '{ "query": "mutation { createUser(authProvider: { email: { email: \"hello@hello\", password: \"hello\" } }) { id } }" }';
    ContentType := ctAPPLICATION_JAVASCRIPT;
  end;
  with RESTRequest1.Params.Add do begin 
    name := ' id ';
    Options := [poAutoCreated];
  end;
  RESTRequest1.Response := RESTResponse1;
  RESTRequest1.SynchronizedEvents := False;

我得到了:a)错误的请求,b)无效的Json查询。

我是如何与Graph.cool API接口的?

1 个答案:

答案 0 :(得分:4)

简单的方法是直接使用HttpClient,比如

function SendHttp(const ARequest: string): string;
var
  HttpClient: THttpClient;
  Response: IHttpResponse;
  ST: TStream;
begin
  HttpClient := THttpClient.Create;
  try
    HttpClient.ContentType := CONTENTTYPE_APPLICATION_JSON;
    HttpClient.Accept := CONTENTTYPE_APPLICATION_JSON;
    ST := TStringStream.Create(ARequest);
    try
      Response := HttpClient.Post('https://api.graph.cool/simple/v1/ENDPOINT', ST, nil,
      TNetHeaders.Create(
        TNameValuePair.Create('Authorization', 'Bearer YOUR_AUTH_TOKEN')
       ));
      Result := Response.ContentAsString();
    finally
      ST.Free;
    end;
  finally
    HttpClient.Free;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Memo1.Lines.Add(SendHttp('{"query": "mutation {'+
      '  createUser('+
      '    authProvider: {' +
      '      email: { email: \"hello@hello.com\", password: \"hello\"'+
      '      }}'+
      '  )' +
      '  {' +
      '    id' +
      '  }' +
      '}" }'));
end;