Jump to content
Sign in to follow this  
Ranja AZ

How to use data-raw json in body with RESTRequest?

Recommended Posts

Hello everyone,

Can someone help me to transform the following cURL request with use of TRESTClient and TRESTRequest:

 

curl --location --request POST 'https://<API server host>/auth/oauth2/token' 
-H 'Content-Type: application/json' 

-H 'Accepte: */*'
--data-raw '{
    "client_id": "013C1A93-3D33-4986-8A7C-773D02C26214",
    "client_secret": "FE8FBA46-6ABF-4DF1-8D5E-31345DAAD194",
    "grant_type": "client_credentials"
}'

 

Regards.

Share this post


Link to post
  var client := TRESTClient.Create('https://<API server host>/auth/oauth2/token');
  try
    var request := TRESTRequest.Create(nil);
    try
      request.Client := client;
      request.Accept := '*/*';
      request.AddBody(
       '{' +
        '"client_id": "013C1A93-3D33-4986-8A7C-773D02C26214",' +
        '"client_secret": "FE8FBA46-6ABF-4DF1-8D5E-31345DAAD194",' +
        '"grant_type": "client_credentials"' +
        '}', TRESTContentType.ctAPPLICATION_JSON);
      request.Execute;
      var response := request.Response;
      if response.Status.Success then
        HandleResponse(response.Content); // this has to be implemented by yourself
    finally
      request.Free;
    end;
  finally
    client.Free;
  end;

 

  • Like 1

Share this post


Link to post

Uwe Raabe,

 

Thank you so much! It's work!

 

After Authorization, I have to execute payment with the following cURL:

 

curl --location --request POST 'https://<API server host>/merchant/v1/payments/'
--header 'Content-Type: application/json'
--header 'Authorization: bearer koeQidreesddfzsbxOXKjccccccc' \
--header 'X-Country: MG'
--header 'X-Currency: MGA'
--data-raw '{
    "reference": "Testing API",
    "subscriber": {
        "country": "MG",
        "currency": "MGA",
        "msisdn": 331170348
    },
    "transaction": {
        "amount": 1000,
        "country":"MG",
        "currency": "MGA",
        "id": "242EB08E-0ACD-445C-8FF7-320FFD85B4A4"
    }
}'

With Postman it's work with status 200. But with following code status is always 401

 

  var client := TRESTClient.Create('https://<API server host>/merchant/v1/payments/');
  try
    var request := TRESTRequest.Create(nil);
    try
      request.Client := client;
      request.Method := TRESTRequestMethod.rmPOST;
      request.Accept := '*/*';

      request.Params.AddItem;
      request.Params[0].Name := 'Autorization';
      request.Params[0].Value := '
bearer koeQidreesddfzsbxOXKjccccccc';
      request.Params[0].Kind := pkHTTPHEADER;

      request.Params.AddItem;
      request.Params[1].Name := 'X-Country';
      request.Params[1].Value := 'MG';
      request.Params[1].Kind := pkHTTPHEADER;

      request.Params.AddItem;
      request.Params[2].Name := 'X-Currency';
      request.Params[2].Value := 'MGA';
      request.Params[2].Kind := pkHTTPHEADER;

      request.AddBody('{"reference": "Testing API","subscriber": {"country": "MG", "currency": "MGA", "msisdn": 331170348}, "transaction": {"amount": 1000, "country":"MG", "currency": "MGA",    "id": "FE9833FE-D5A3-4450-9786-90735F75EBFB"}}', TRESTContentType.ctAPPLICATION_JSON);


      request.Execute;
      var response := request.Response;

 

Is there error in my code? 

 

Regard!

 

Share this post


Link to post

Are you missing the application/json content type?
Or is it an authentication issue - the 401 seems to indicate that.

Share this post


Link to post

by adding the following lines

 

      request.Params.AddItem;
      request.Params[3].Name := 'Content-Type';
      request.Params[3].Value := 'application/json';
      request.Params[3].Kind := pkHTTPHEADER;

 

result is the same: status 401

Share this post


Link to post

You spelled Authorization wrong.

Quote

request.Params[0].Name := 'Autorization';

Have you considered using a TOAuth2Authenticator instance linked to the client?

 

 var client := TRESTClient.Create('https://<API server host>/merchant/v1/payments/');
 try
   var auth := TOAuth2Authenticator.Create(client); // the client will free the authenticator
   auth.TokenType := TOAuth2TokenType.ttBEARER;
   auth.AccessToken := 'koeQidreesddfzsbxOXKjccccccc';
   client.Authenticator := auth;
   var request := TRESTRequest.Create(nil);

Adding the header parameters can also be simplified:

    request.AddParameter('X-Country', 'MG', pkHTTPHEADER);
    request.AddParameter('X-Currency', 'MGA', pkHTTPHEADER);

 

Share this post


Link to post

You can try with refit unit https://github.com/viniciusfbb/ipub-refit

The implementation could be something like this:

 

unit MerchantApi;

interface

uses
  iPub.Rtl.Refit; // https://github.com/viniciusfbb/ipub-refit

type
  TCountry = (MG);
  TCurrency = (MGA);

  TPaymentSubscriber = record
    Country: TCountry;
    Currency: TCurrency;
    Msisdn: Cardinal;
  end;

  TPaymentTransaction = record
    Amount: Integer;
    Country: TCountry;
    Currency: TCurrency;
    Id: string;
  end;

  TPaymentRequest = record
    Reference: string;
    Subscriber: TPaymentSubscriber;
    Transaction: TPaymentTransaction;
  end;

  [BaseUrl('https://API_server_host/merchant/v1')]
  IMerchantApi = interface(IipRestApi)
    ['{1D10C463-1567-4DE0-88F2-099CC0442E43}']

    [Post('/payments')]
    [Headers('Authorization', 'Bearer {AuthToken}')]
    [Headers('X-Country', '{XCountry}')]
    [Headers('X-Currency', '{XCurrency}')]
    function Payments(AXCountry: TCountry; AXCurrency: TCurrency; const ABody: TPaymentRequest): string;

    function GetAuthToken: string;
    procedure SetAuthToken(const AValue: string);
    property AuthToken: string read GetAuthToken write SetAuthToken;
  end;

var
  FMerchantApi: IMerchantApi;

implementation

initialization
  FMerchantApi := GRestService.&For<IMerchantApi>;
end.

 

And your code could be this:

 

 

uses
  MerchantApi;

procedure TForm1.FormCreate(Sender: TObject);
var
  LPaymentRequest: TPaymentRequest;
begin
  LPaymentRequest.Reference := 'Testing API';
  LPaymentRequest.Subscriber.Country := TCountry.MG;
  LPaymentRequest.Subscriber.Currency := TCurrency.MGA;
  LPaymentRequest.Subscriber.Msisdn := 331170348;
  LPaymentRequest.Transaction.Amount := 1000;
  LPaymentRequest.Transaction.Country := TCountry.MG;
  LPaymentRequest.Transaction.Currency := TCurrency.MGA;
  LPaymentRequest.Transaction.Id := 'FE9833FE-D5A3-4450-9786-90735F75EBFB';

  FMerchantApi.AuthToken := 'koeQidreesddfzsbxOXKjccccccc';
  ShowMessage(FMerchantApi.Payments(TCountry.MG, TCurrency.MGA, LPaymentRequest));
end;

 

Share this post


Link to post

Looks like you didn't check the Do Not Encode for the parameters.

 

When using the Bearer Authenticator this is handled internally. If you want to add the parameter manually you can do like this:

        request.AddAuthParameter(HTTP_HEADERFIELD_AUTH, 'Bearer ' + <YourAccessToken>,
          TRESTRequestParameterKind.pkHTTPHEADER, [TRESTRequestParameterOption.poDoNotEncode]);

The HTTP_HEADERFIELD_AUTH is declared in REST.Consts.pas.

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×