0

I'm using the TWebHttpRequest component in TMS WEB Core to do an API call, but I'm not sure how to get the status codes of the response.

This is the current code that I use to do the API call using the TWebHttpRequest component:

procedure SendEmail(Sender, MailSubject, MailBody, recipients, cc: String);
var
  Email: TWebHttpRequest;
begin
  Email := TWebHttpRequest.Create(nil);

  Email.URL := 'MY_ENDPOINT_URL_FOR_SENDING_EMAIL...';

  Email.Command := httpPOST;
  Email.Headers.Clear;
  Email.Headers.AddPair('Content-Type','application/json');
  Email.PostData := '{' +
    '"Sender": "' + Sender + '",' +
    '"MailSubject": "' + MailSubject + '",' +
    '"MailBody": "' + MailBody + '",' +
    '"recipients": "' + recipients + '",' +
    '"cc": "' + cc + '"' +
  '}';

  Email.Execute(
    procedure(AResponse: string; AReq: TJSXMLHttpRequest)
    begin
      Email.Free;
    end
  );
end;

What I need is the status and/or error codes on the response (200=ok, 403=forbidden, 404=not_found, etc.)

How can I get the status codes when using TWebHttpRequest?

3
  • You can parse AResponse Commented May 14, 2024 at 8:44
  • @JohnEasley AResponse only contains my custom JSON. It doesn't contain the status codes. At least not with my API calls. As an example, my AResponse contains {"value": "Email Sent"} Commented May 14, 2024 at 9:18
  • 1
    When I create my APIs, I aways at a status pair to the response, because I may have more response codes than the typical. Commented May 15, 2024 at 20:10

1 Answer 1

1

I found this post explaining how to get status codes and they're saying this way:

procedure TForm1.WebHttpRequest1RequestResponse(Sender: TObject;
  ARequest: TJSXMLHttpRequestRecord; AResponse: string);
begin
  if (ARequest.req.Status = '404') then
     ...
  if (ARequest.req.Status = '200') then
     ...
end;

But that wasn't useful to me as I wanted the status codes within the Execute procedure. So I ended up finding out that you can get the status codes through the AReq: TJSXMLHttpRequest parameter as well.

  • Req.Status for status codes (200, 403, 404, etc.)
  • AReq.StatusText for status text (ok, forbidden, not found, etc.)
Email.Execute(
  procedure(AResponse: string; AReq: TJSXMLHttpRequest)
  begin
    console.log('Status: ' + AReq.Status.ToString);
    console.log('StatusText: ' + AReq.StatusText);
  end
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.