Search code examples
restdelphifiremonkey

REST API and Delphi error: Required OAuth credentials not provided


I need to implement a REST API in FireMonkey to get some information, but I'm not sure how I can do it.

The REST API uses OAuth2, I have the ACESS_TOKEN but is not working

<ams:fault xmlns:ams="http://wso2.org/apimanager/security"><ams:code>900902</ams:code><ams:message>Missing Credentials</ams:message><ams:description>Required OAuth credentials not provided. Make sure your API invocation call has a header: "Authorization: Bearer ACCESS_TOKEN"</ams:description></ams:fault>
var
  LClient: TRESTClient;
  LRequest: TRESTRequest;
  LResponse: TRESTResponse;

begin
  LClient := TRESTClient.Create('https://apigateway.serpro.gov.br/consulta-cnpj- 
   df/v1/cnpj/99999999999999');
  
  try
    LRequest := TRESTRequest.Create(LClient);
     try
      LResponse := TRESTResponse.Create(LClient);
      try
        LRequest.Client := LClient;  
        LRequest.Response := LResponse;

        LRequest.Accept:='application/json';
        LRequest.Params.AddHeader('Authorization', 'Bearer 6315a3c9c2e4bb2e0816da132828f269');

        LRequest.Method := rmGET;
   
        LRequest.Execute;

        Memo1.Clear;
        Memo1.Lines.Add(IntToStr(LResponse.StatusCode) + ' / ' + LResponse.StatusText);
        Memo1.Lines.Add(LResponse.Headers.Text);
        Memo1.Lines.Add('--------------------------------------------------------------');
        Memo1.Lines.Add(LResponse.Content);
      finally
        LResponse.Free;
      end;
    finally
      LRequest.Free;
    end;
  finally
    LClient.Free;
  end;
end;

Can someone help me?


Solution

  • The Auth header needs to be sent without encoding, so use AddItem instead of AddHeader

    LRequest.Params.AddItem ('Authorization', 'Bearer ' + YourToken, pkHTTPHEADER, [poDoNotEncode]);
    

    Embarcadero REST framework can be confusing. I haven't worked with REST for long either, so still struggling with it myself.