Home > front end >  Issue posting JSON Data with REST AddBody method
Issue posting JSON Data with REST AddBody method

Time:09-29

I'm having trouble with a POST request to an API which I am not the owner of.

The request must simply post JSON data. Please have a look:

var 
  RESTRequest : TRESTRequest;
  RESTClient : TRESTClient;
  Response : TRESTResponse;
  contract : TJSONObject;

begin
  RESTClient := TRESTClient.Create('URL');
  try 
    RESTRequest := TRESTRequest.Create(nil);
    try               
      contract := TJSONObject.Create;
      contract.AddPair(TJSONPair.Create('name','my_first_contract.pdf'));
      
      RESTRequest.Client := RESTClient;
      RESTRequest.Method := rmPOST;
      RESTRequest.Accept := 'application/json';
      RESTRequest.AddParameter('j_token','mytoken',pkHTTPHEADER,poDoNotEncode);
      RESTRequest.AddBody(contract);
      RESTRequest.Execute;
      Response := RESTRequest.Response;
      ShowMessage(Response.StatusText   ' : '   Response.Content);
  
    finally
      RESTRequest.Free;
    end;
  finally
    RESTClient.Free; 
  end;
end; 

I obtained this error :

Not Found : {"errors":"Fatal error in JsonConvert. Passed parameter json object in JsonConvert.deserializeObject() is not of type object.\n"}

I've read online that the AddBody() method first serializes its content if it's an object. In this case, the content of the body is my TJSONObject, but when I try to replace that with a String, like this:

var
  contract : String;
  ...
begin
  contract := '{"name":"my_first_contract.pdf"}';
  ...
  RESTRequest.AddBody(contract, ctAPPLICATION_JSON);
  ...
end; 

I'm getting the exact same error.

So, does that mean that a TJSONObject is not viewed as an Object for the JsonConvert.deserializeObject() method ? Or, is the serialization of the AddBody() messed up?

CodePudding user response:

The problem was on the 'j_token' header : as I was trying to solve it, some friends wanted to help me but I didn't want to give them the access token because it's exclusive to my company. They still tried to access the api with a false token wich resulted with the same error as I was getting :

Not Found : {"errors":"Fatal error in JsonConvert. Passed parameter json object in JsonConvert.deserializeObject() is not of type object.\n"}

Thanks to that I could deduce that the issue was on the j_token. After setting up my own api I could watch what was I posting and then I saw that my 'j_token' header was still getting encoded even though I added the poDoNotEncode options to my AddParameter method.

I created a new post on this forum to look for that poDoNotEncode error if you ever stumble upon this same problem : Trouble with poDoNotEncode option in TRESTRequest.AddParameter() method

  • Related