I am trying to use the GitHub API with the Delphi REST components to create a file in a repo. I have successfully done this from Python and a curl call, but after much effort, I can't seem to get it to work from Delphi using the provided REST components. I have successfully done GETs using the Delphi components. The curl command that works is:
curl -X PUT \
-H "Authorization: token ghp_xxxxxxxxxxxxxxxxxxxxxxxx"
https://api.github.com/repos/<user>/TestRepo/contents/test.txt \
-d '{"message": "Add File", "content": "bXkgbmV3IGZpbGUgY29udGVudHM="}'
I've swapped out the user name and hidden the token but this call works.
The equivalent Delphi code I used was:
procedure TfrmMain.addFile;
begin
RESTClient1.BaseURL := 'https://api.github.com';
RESTRequest1.Client := RESTClient1;
RESTRequest1.Resource := '/repos/<user>/TestRepo/contents/test.txt';
RESTRequest1.Method := rmPUT;
RESTRequest1.AddParameter('Authorization', 'ghp_xxxxxxxxxxxxxxxxx', pkHTTPHEADER);
RESTRequest1.AddParameter('message', 'Add File', pkREQUESTBODY);
RESTRequest1.AddParameter('content', 'bXkgbmV3IGZpbGUgY29udGVudHM=', pkREQUESTBODY);
RESTRequest1.Execute;
Memo1.text := RESTResponse1.JSONValue.ToString;
end;
The response I get is:
{"message":"Not
Found","documentation_url":"https:\/\/docs.github.com\/rest\/reference\/repos#create-or-
update-file-contents"}
I've also tried using the Delphi REST Debugger, and I get the same error message.
I tried changing
RESTRequest1.AddParameter('Authorization', 'ghp_xxxxxxxxxxxxxxxxx', pkHTTPHEADER);
to
RESTRequest1.AddParameter('Authorization', 'token ghp_xxxxxxxxxxxxxxxxx', pkHTTPHEADER);
just in case that was the issue but no difference. Any suggestions?
CodePudding user response:
The use of AddParameter for the body is wrong. The resulting content will not automatically be JSON. Try it this way:
RESTClient1.BaseURL := 'https://api.github.com';
RESTRequest1.Client := RESTClient1;
RESTRequest1.Resource := 'repos/<user>/TestRepo/contents/test.txt';
RESTRequest1.Method := rmPUT;
RESTRequest1.AddAuthParameter('Authorization', 'token ghp_xxxxxxxxxxxxxxxxx', pkHTTPHEADER, [poDoNotEncode]);
RESTRequest1.AddBody(TJSONObject.Create.AddPair('message', 'Add File').AddPair('content', 'bXkgbmV3IGZpbGUgY29udGVudHM='), ooREST);
RESTRequest1.Execute;