Use the different HTTP classes and their functions

Completed

You can access REST services through HTTP requests. To implement an HTTP request, you need to use an HTTP verb.

The following verbs are the most-used verbs in REST services:

  • GET (to read data)

  • POST (to create data)

  • PUT (to update/replace data)

  • PATCH (to update/modify data)

  • DELETE (to delete data)

HttpClient class

The HttpClient class provides a base class for sending HTTP requests and receiving HTTP responses from a resource that is identified by a URI.

  • DefaultRequestHeaders() - Gets the default request headers that should be sent with each request.

  • SetBaseAddress(Uri) - Sets the base address of the URI that is used when you're sending requests.

  • GetBaseAddress() - Gets the base address of the URI that is used when you're sending requests.

  • Get(Uri, HttpResponseMessage) - Sends a GET request to get the resource that is identified by the request URI.

  • Post(Uri, HttpContent, HttpResponseMessage) - Sends a POST request to the specified URI.

  • Put(Uri, HttpContent, HttpResponseMessage) - Sends a PUT request to the specified URI.

  • Patch(Uri, HttpContent, HttpResponseMessage) - Sends a PATCH request to the specified URI.

  • Delete(Uri, HttpResponseMessage) - Sends a DELETE request to the specified URI.

  • Send(HttpRequestMessage, HttpResponseMessage) - Sends an HTTP request. In the HttpRequestMessage variable, you must provide the URI and the verb to use.

  • Clear() - Sets the HttpClient variable to the default value.

  • Timeout() - Gets or sets the duration in milliseconds to wait before the request times out. Timeout is a Duration value. If you don't set it, the default value of 100000 ms (100 seconds) is used.

  • AddCertificate(Certificate, Password) - Adds a certificate to the HttpClient class. You need to provide a base64 encoded certificate. An overload that takes SecretText parameters is available, and we recommend that you use it so that the certificate and password aren't exposed to the debugger.

  • UseResponseCookies(UseResponseCookies) – When this option is set to true, the client automatically attaches cookies it received from the response to all next requests.

  • UseServerCertificateValidation(Validate) – Controls whether the client validates the server certificate of the endpoint that you call. Validation is enabled by default, so only set this option to false if your app must call an endpoint whose certificate can't be validated.

When providing a URI, you can use two approaches. The first approach is to request data from the following URL:

https://jsonplaceholder.typicode.com/posts

Then, you can use the SetBaseAddress when you're using the HttpClient class to perform multiple requests.

var
    client: HttpClient;
    responseMessage: HttpResponseMessage;
begin 
    client.SetBaseAddress('https://jsonplaceholder.typicode.com/');
    client.Get('posts', responseMessage);
end;

The second approach is for when you're only requesting the data once. In that case, you can put the full URI in the Get function.

var
    client: HttpClient;
    responseMessage: HttpResponseMessage;
begin 
    client.Get('https://jsonplaceholder.typicode.com/posts', responseMessage);
end;

HttpHeaders class

The HttpHeaders class contains a collection of headers and their values. HttpHeaders are sent with every request and response, and they are used to send extra information about the request or how the client wants the response to be formatted.

Common HttpHeaders are Authorization (used to send authentication credentials), Content-Type (the media type of the body of the request), User-Agent (the user agent string, the name of the browser), Accept-Charset (which character sets are acceptable).

Headers are split into two groups. Request headers, such as Authorization and Accept, describe the request itself. Content headers, such as Content-Type, describe the body that you send. You must add each header to the correct collection, otherwise the service that you call typically answers with a 415 Unsupported Media Type or 412 Precondition Failed status code.

You can get the request HttpHeaders that are sent with every request by using the DefaultRequestHeaders property from the HttpClient class, or the GetHeaders method on a single HttpRequestMessage. The content headers are retrieved with the GetHeaders method on the HttpContent class.

var
    client: HttpClient;
    headers: HttpHeaders;    
    content: HttpContent;
    contentHeaders: HttpHeaders;
    responseMessage: HttpResponseMessage;
begin 
    headers := client.DefaultRequestHeaders();
    headers.Add('Accept', 'application/json');

    content.GetHeaders(contentHeaders);
    contentHeaders.Clear();
    contentHeaders.Add('Content-Type', 'application/json');

    client.Post('https://jsonplaceholder.typicode.com/posts', content, 
                responseMessage);
end;
  • Add(Key, Value) - Sets the provided value for the provided header name. The value is validated. An overload that takes a SecretText value is available for sensitive headers, such as Authorization.

  • TryAddWithoutValidation(Key, Value) - Adds the header without validating the value. Use this method for services that expect header values that don't follow the HTTP standard.

  • Clear() - Sets the HttpHeaders variable to the default value.

  • Contains(Key) - Checks if an HttpHeaders variable contains a property with the given key.

  • ContainsSecret(Key) - Checks if the header with the given key holds a secret value.

  • Keys() - Gets the key name of all the headers.

  • GetValues(Key, Array of Text) - Get the values for the specified key. The values are returned in the array of text.

  • GetSecretValues(Key, Array of SecretText) - Gets the values for a header that was added as a SecretText value. Secret header values can't be read back as plain text.

  • Remove(Key) - Removes the key and the related values from the HttpHeaders object.

HttpResponseMessage class

The HttpResponseMessage class represents an HTTP response message. A response message is the result of an HTTP action (Get, Post, Put, Patch, Delete, or Send). It's returned in the HttpResponseMessage parameter.

var
    client: HttpClient;
    responseMessage: HttpResponseMessage;
begin 
    client.Get('https://jsonplaceholder.typicode.com/posts', responseMessage);
end;
  • Content() - Gets the contents (HttpContent) of the HTTP response.

  • Headers() - Gets the HTTP request's HTTP headers.

  • HttpStatusCode() - Gets the status code of the HTTP response.

  • IsSuccessStatusCode() - Gets a value that indicates if the HTTP response was successful.

  • ReasonPhrase() - Gets the reason phrase that is typically sent together with the status code. You can use this variable to give the user extra information when a request failed.

Common HTTP status error codes

When a web service endpoint is called, you always receive an HTTP status code as part of the response. You can retrieve this in AL by calling the HttpStatusCode() procedure, part of the HttpResponseMessage class.

We can categorize the status codes in five groups:

  • 1xx – These codes are informational. The request was received, and the process continues.

  • 2xx – The server successfully received and accepted the request. A status code 200 indicates OK, while 201 is often used when a record has been Created.

  • 3xx – Are used to indicate that the requested resource has been moved or redirected to another location.

  • 4xx – There's an error on the client side. The request contains an error. This code could range from 400 (Bad Request) (for example when using wrong JSON data/structure), 401 (Access denied) when the request lacks valid credentials, 403 (Forbidden) when an access restriction policy blocks the resource, 405 (Method Not Allowed) when the endpoint doesn't support the verb that you used, and 415 (Unsupported Media Type) when the Content-Type header doesn't match what the endpoint expects, to a 404 (Not Found), when the resource can't be located due to an error in the URL. A 429 (Too Many Requests) indicates that you're calling the service too aggressively and should retry later.

  • 5xx – There's an error on the server side. A status code 500 (Internal Server Error) indicates that the server couldn't process the request due to an unexpected condition. A 503 indicates that the service is down and unavailable.

The easiest way to handle these status codes is to use the IsSuccessStatusCode() procedure on the HttpResponseMessage. This returns a Boolean value that specifies if the request returned an error or not.

HttpContent class

The HttpContent class represents an HTTP body and content headers, and it's used as the body to send information or as a response body. You can use the Content property on the HttpRequestMessage (with a request) or the HttpResponseMessage (with a response) classes. By default, the content headers contain a Content-Type header with the value text/plain; charset=utf-8. Change this value whenever the endpoint expects another media type, such as application/json.

  • Clear() - Sets the HttpContent object to a default value.

  • GetHeaders(HttpHeaders) - Gets the content's HTTP headers. The result is returned in the HttpHeaders parameter.

  • ReadAs(Result) - Reads the content into the provided text or stream. The result can be of type Text, InStream, or SecretText.

  • WriteFrom(Value) - Sets the HttpContent variable to the provided text or stream. You can also write from a SecretText value when the body contains credentials.

  • IsSecretContent() - Indicates whether the content is secret. Secret content can only be read as a SecretText value.

HttpRequestMessage class

The HttpRequestMessage class represents an HTTP request message. A request message is the class that is used to send a request.

[Ok := ] HttpClient.Send(HttpRequestMessage, HttpResponseMessage);
  • Content() - Gets/sets the contents of the HTTP request.

  • GetHeaders(HttpHeaders) - Gets a reference to the collection of request headers for this specific request.

  • GetRequestUri() - Gets the URI that is used for the HTTP request.

  • Method() - Gets or sets the method type. You must provide an HTTP verb that is used with this request.

  • SetRequestUri(RequestUri) - Sets the URI that is used for the HTTP request.

  • SetSecretRequestUri(SecretText) - Sets the URI as a SecretText value. Use this method when the URI contains an API key or another secret. The URI can only be read back with GetSecretRequestUri.

  • SetCookie, GetCookie, GetCookieNames, and RemoveCookie - Manage the cookies that are sent with the request.

var
    client: HttpClient;
    requestMessage: HttpRequestMessage;
    responseMessage: HttpResponseMessage;
begin 
    requestMessage.Method('GET');
    requestMessage.SetRequestUri('https://jsonplaceholder.typicode.com/posts');
    client.Send(requestMessage, responseMessage);
end;