Qore RestClient Module Reference 2.2.0
All Classes Namespaces Functions Variables Modules Pages
RestClient::RestClient Class Reference

this class provides the REST client API More...

#include <RestClient.qm.dox.h>

Inheritance diagram for RestClient::RestClient:
[legend]

Public Member Methods

 addDefaultHeaders (hash< auto > h)
 adds default headers to each request
 
 clearAltTokenSigner ()
 Clears alt token signer code and the header for it.
 
 clearConnectionPath ()
 Clears the connection path when a validator is present that manages the URI path.
 
 constructor (*hash< auto > opts, *softbool do_not_connect)
 calls the base class HTTPClient constructor and optionally connects to the REST server
 
hash< auto > del (string path, auto body, *reference< hash< auto > > info, *hash< auto > hdr)
 sends an HTTP DELETE request to the REST server and returns the response
 
hash< auto > doRequest (string m, string path, auto body, *reference< hash< auto > > info, softbool decode_errors=True, *hash< auto > hdr)
 sends an HTTP request to the REST server and returns the response
 
hash< auto > doSignedRequest (string shdr, code signer, string m, string path, auto body, *reference< hash< auto > > info, softbool decode_errors=True, *hash< auto > hdr)
 sends a signed HTTP request to the REST server and returns the response
 
hash< auto > doValidatedRequest (string m, string path, auto body, *reference< hash< auto > > info, softbool decode_errors=True, *hash< auto > hdr)
 The same as doRequest() except no schema validation is performed on the request.
 
hash< auto > get (string path, auto body, *reference< hash< auto > > info, *hash< auto > hdr)
 sends an HTTP GET request to the REST server and returns the response
 
hash< auto > getDefaultHeaders ()
 returns the hash of default headers to sent in all requests
 
*LoggerInterface getLogger ()
 Returns the logger interface for logging.
 
hash< auto > getNewToken ()
 Get a new token from the server either with an OAuth2 token request or using the refresh token.
 
hash< auto > getOAuth2Options ()
 Return OAuth2 options.
 
*string getSendEncoding ()
 returns the current data content encoding (compression) object or NOTHING if no encoding option is set
 
string getSerialization ()
 returns the current data serialization format currently in effect for the object
 
*string getToken ()
 Returns any token set for the connection.
 
string getTokenType ()
 Returns the token type for any token.
 
RestSchemaValidator::AbstractRestSchemaValidator getValidator ()
 returns the current validator object
 
hash< auto > gotOAuth2LoginInfo (hash< auto > h, *bool refresh)
 Called when OAuth2 login information has been received.
 
bool isAuthTokenError (int status_code, hash< auto > headers, *bool body_deserialized, *string body_content_type, auto body)
 Returns True if the response was related to an authorization token error.
 
bool needsRestBodyAuthErrorCheck ()
 Returns True if the object needs to have deserialized bodies check for authentication errors.
 
hash< auto > patch (string path, auto body, *reference< hash< auto > > info, *hash< auto > hdr)
 sends an HTTP PATCH request to the REST server and returns the response
 
hash< auto > post (string path, auto body, *reference< hash< auto > > info, *hash< auto > hdr)
 sends an HTTP POST request to the REST server and returns the response
 
 prepareToSend (string method, reference< string > path, reference< auto > body, *reference< hash< auto > > hdr)
 Prepares and processes message parameters for sending without sending the message.
 
auto preprocessRequestBody (auto request_body)
 Preprocesses the request body before serialization.
 
hash< auto > processRestResponse (hash< auto > resp, string method, string path, *reference< hash< auto > > info)
 Process the raw REST response received.
 
hash< auto > put (string path, auto body, *reference< hash< auto > > info, *hash< auto > hdr)
 sends an HTTP PUT request to the REST server and returns the response
 
 replaceDefaultHeaders (*hash< auto > hdr)
 replaces default headers
 
bool requiresOAuth2Token ()
 Returns True if the client requires an OAuth2 token.
 
bool requiresRefresh ()
 Returns True if the client requires a tokenm refresh.
 
 setAltTokenSigner (code signer, string signer_header)
 Sets alt token signer code and the header for it.
 
 setContentEncoding (string enc='auto')
 sets the request and desired response encoding for the object; see EncodingSupport for valid options
 
 setLogger (*LoggerInterface logger)
 Accepts a LoggerInterface object for logging (or clears it)
 
 setOAuth2Options (hash< auto > new_opts)
 Sets OAuth2 options.
 
 setSendEncoding (string enc='auto')
 change the data content encoding (compression) option for the object
 
 setSerialization (string data='auto')
 change the serialization option for the object; see DataSerializationOptions for valid options
 
 setToken (string token_type, string token, *string refresh_token, *date token_expiry)
 Sets a token for authentication.
 
 setValidator (RestSchemaValidator::AbstractRestSchemaValidator validator)
 Sets a new REST schema validator.
 
AbstractPollOperation startOAuth2PollRefreshToken ()
 Starts an OAuth2 refresh token request in a non-blocking I/O operation.
 
AbstractPollOperation startOAuth2PollSendRecv ()
 Starts an OAuth2 token request in a non-blocking I/O operation.
 
bool usingOAuth2 ()
 Returns True if the client is configured for authentication with OAuth2.
 

Static Public Member Methods

static *string getScopeString (*list< auto > scopes, string separator=' ')
 Returns a scope string URI argument.
 

Public Attributes

const Accept = AcceptList.join(",")
 Accept header value.
 
const AcceptList = ...
 Accept header list.
 
const AcceptMap = map {$1: True}
 Map of acceptable Mime types.
 
const CompressionThreshold = 1024
 default threadhold for data compressions; transfers smaller than this size will not be compressed
 
const DataSerializationOptions = ...
 Data serialization options; this is a hash to simulate a set of strings.
 
const DataSerializationSupport = ...
 Data serialization support mapping codes to MIME types and de/serialization functions.
 
const DefaultHeaders = ...
 default HTTP headers (Content-Type is added before sending)
 
const DefaultOAuth2RedirectUrl = "auto"
 Default oauth2_redirect_url option value.
 
const DefaultOptions = ...
 Default option values.
 
const EncodingSupport = ...
 Send content encoding options.
 
const MinimumTokenRefresh = 1m
 Minimum time between OAuth2 token requests.
 
const OAuth2AuthHeaders = ...
 Headers to send when making an authorization / token request.
 
const OAuth2GrantOptions = ...
 Option requirements per OAuth2 grant type.
 
const Oauth2TokenRefreshWindow = 10m
 Refresh a new token 10 minutes before it expires.
 
const Version = "2.2"
 RestClient Version.
 
const VersionString = sprintf("Qore-RestClient/%s", RestClient::Version)
 RestClient Version String.
 

Private Member Methods

 checkLogin (*reference< hash< auto > > info)
 Checks if a login is necessary; if so, then the login is performed.
 
 checkOAuth2Options (hash< auto > opts, *bool no_exceptions)
 Validates and sets any OAuth2 options.
 
hash< auto > doOAuth2LoginRequest (string url, hash< auto > login, *reference< hash< auto > > info)
 Returns the deserialized response body of an OAuth2 authorization / token request.
 
hash< auto > doRequestIntern (string m, string path, auto body, *reference< hash< auto > > info, softbool decode_errors=True, *hash< auto > hdr, *string assume_content_type, *string shdr, *code signer)
 Makes a REST request and returns the result.
 
hash< auto > getNewTokenIntern (*reference< hash< auto > > info)
 Get a new token from the server.
 
*hash< auto > getOAuth2AuthHeaders ()
 Returns headers to use with OAuth2 authorization / token requests.
 
hash< auto > getOAuth2LoginInfo (string grant_type)
 Returns an OAuth2 login hash.
 
hash< auto > getOAuth2RefreshInfo ()
 Returns an OAuth2 refresh hash.
 
*hash< auto > getUpdateOptionsAfterLogin (hash< auto > h, *bool refresh)
 Returns options to update after an OAuth2 login.
 
hash< auto > loginIntern (*reference< hash< auto > > info)
 Authenticates with OAuth2 if configured.
 
bool needsRefresh (*hash< ExceptionInfo > ex, *hash< auto > info, *bool body_deserialized, auto body)
 Returns True if the request error indicates that a refresh operation should be performed.
 
hash< auto > oauth2Auth (hash< auto > login, *reference< hash< auto > > info, *bool refresh)
 Perform OAuth2 authentication.
 
hash< auto > oauth2AuthIntern (hash< auto > login, *reference< hash< auto > > info, *bool refresh)
 Perform OAuth2 authentication.
 
nothing prepareMsg (string method, string path, reference< auto > body, reference< hash< auto > > hdr, string ct='Content-Type')
 sets up the Content-Type header and encodes any body for sending
 
nothing preparePath (reference< string > path)
 sets up the path for the HTTP request URI
 
hash< auto > refreshTokenIntern (*reference< hash< auto > > info)
 Gets a new token using the refresh token.
 
hash< auto > sendAndDecodeResponse (*data body, string m, string path, hash< auto > hdr, *reference< hash< auto > > info, *softbool decode_errors, *string assume_content_type, *string shdr, *code signer)
 sends the outgoing HTTP message and recodes the response to data
 
 setOAuth2LoginInfo (hash< auto > h)
 Sets options from the OAuth2 login response on the local object.
 
 setupAuth (hash< auto > opts, *bool no_exceptions)
 Sets up authentication info.
 
AbstractPollOperation startOAuth2AuthPoll (hash< auto > login)
 Starts a non-blocking I/O operation to authenticate with an OAuth2 server and acquire an auth token.
 

Static Private Member Methods

static decodeError (hash< auto > h, *reference< hash< auto > > info)
 decode any REST errors returned if possible
 

Private Attributes

transient *code alt_token_signer
 To use to sign requests to the any alt token URL.
 
transient *string alt_token_signer_header
 The header for the alt token signer.
 
string oauth2_alt_token_url
 Alternate OAuth2 token URL.
 
*hash< auto > oauth2_alt_url_subst
 Alternate OAuth2 URL substitution info.
 
string oauth2_app
 OAuth2 app name.
 
*hash< auto > oauth2_auth_args
 OAuth2 extra auth args.
 
string oauth2_auth_url
 OAuth2 auth URL.
 
bool oauth2_auto_refresh = True
 If OAuth2 tokens should be automatically refreshed.
 
string oauth2_client_id
 OAuth2 client ID.
 
string oauth2_client_secret
 OAuth2 client secret.
 
string oauth2_grant_type
 OAuth2 grant type.
 
bool oauth2_pkce = False
 If PKCE should be used with the OAuth2 authorization_code flow.
 
string oauth2_redirect_url
 OAuth2 redirect URL.
 
string oauth2_scope_separator_char
 OAuth2 scope separator char.
 
*softlist< string > oauth2_scopes
 OAuth2 scope.
 
*hash< auto > oauth2_token_args
 OAuth2 extra token args.
 
bool oauth2_token_auth_secret_only = False
 If HTTP basic authentication should be used with the client_secret only when making token requests.
 
date oauth2_token_expiry
 The token expiry date.
 
int oauth2_token_expiry_hint
 An expiry date hint as a value in minutes.
 
string oauth2_token_url
 OAuth2 token URL.
 
bool oauth2_token_use_basic_auth = False
 If HTTP basic authentication should be used with the client_id and client_secret when making token requests.
 
string password
 password for authentication
 
string refresh_token
 Any refresh token granted to the client.
 
*hash< auto > rest_body_auth_error_check
 A hash to check all deserialized bodies in 200 OK server responses for authentication errors.
 
string token
 Any token set for the connection; will be passed as a bearer token (Authorization: Bearer ...)
 
string token_api_key_header
 If this option is set along with a token, it indicates a header to send the token in as an API key.
 
date token_timestamp
 Last timestamp for token acquisition.
 
string token_type
 The token type, if any.
 
string username
 username for authentication
 

Static Private:Internal Member Methods

static tryDecodeErrorResponse (reference< hash< auto > > h, *reference< hash< auto > > info)
 tries to decode an error response
 

Detailed Description

this class provides the REST client API

Member Function Documentation

◆ addDefaultHeaders()

RestClient::RestClient::addDefaultHeaders ( hash< auto >  h)

adds default headers to each request

Example:
# disable gzip and bzip encoding in responses
rest.addDefaultHeaders({"Accept-Encoding": "compress"});
Parameters
ha hash of headers to add to the default headers to send on each request
Note
default headers can also be set in the constructor

Headers added here will be sent in all requests but can be overridden in requests as well.

See also
RestClient::getDefaultHeaders()
Since
RestClient 1.3

◆ checkOAuth2Options()

RestClient::RestClient::checkOAuth2Options ( hash< auto >  opts,
*bool  no_exceptions 
)
private

Validates and sets any OAuth2 options.

Since
RestClient 2.0

◆ clearAltTokenSigner()

RestClient::RestClient::clearAltTokenSigner ( )

Clears alt token signer code and the header for it.

Since
RestClient 2.2

◆ clearConnectionPath()

RestClient::RestClient::clearConnectionPath ( )

Clears the connection path when a validator is present that manages the URI path.

Called from the constructor when a REST validator is present that manages the URI path

◆ constructor()

RestClient::RestClient::constructor ( *hash< auto >  opts,
*softbool  do_not_connect 
)

calls the base class HTTPClient constructor and optionally connects to the REST server

Example:
RestClient rest({"url": "http://localhost:8001/rest"});
Parameters
optsvalid options are:
  • additional_methods: Optional hash with more but not-HTTP-standardized methods to handle. It allows to create various HTTP extensions like e.g. WebDAV. The hash takes the method name as a key, and the value is a boolean True or False: indicating if the method can accept a message body as well. Example:
    # add new HTTP methods for WebDAV. Both of them require body posting to the server
    ("additional_methods": ("PROPFIND": True, "MKCOL": True ));
  • connect_timeout: The timeout value in milliseconds for establishing a new socket connection (also can be a relative date-time value for clarity, ex: 20s)
  • content_encoding: for possible values, see EncodingSupport; this sets the send encoding (if the "send_encoding" option is not set) and the requested response encoding (note that the RestClient class will only compress outgoing message bodies over CompressionThreshold bytes in size)
  • data: a data serialization option; if not present defaults to "auto"
  • default_path: The default path to use for new connections if a path is not otherwise specified in the connection URL
  • default_port: The default port number to connect to if none is given in the URL
  • error_passthru: if True then HTTP status codes indicating errors will not cause a REST-RESPONSE-ERROR exception to be raised, rather such responses will be passed through to the caller like any other response
  • headers: an optional hash of headers to send with every request, these can also be overridden in request method calls
  • http_version: Either '1.0' or '1.1' for the claimed HTTP protocol version compliancy in outgoing message headers
  • logger: any logger to use for the object
  • max_redirects: The maximum number of redirects before throwing an exception (the default is 5)
  • oauth2_alt_url_subst: URL substitution info for oauth2_alt_token_url
  • oauth2_alt_token_url: Alternate token URL; if this is set then the token request is made to this URL with the oauth2_token_url value as an argument in the request
  • oauth2_auto_refresh: If OAuth2 tokens should be automatically refreshed (default True)
  • oauth2_auth_args: Extra arguments for OAuth2 authentication requests to oauth2_auth_url for the authentication_code grant type. Note that the authorization_code grant type requires external user authorization to acquire an access token
  • oauth2_auth_url: The OAuth2 authorization URL for the authorization_code grant type; ignored if the token option is set. Note that the authorization_code grant type requires external user authorization to acquire an access token
  • oauth2_client_id: The OAuth2 client ID; ignored if the token option is set
  • oauth2_client_secret: the OAuth2 client secret; ignored if the token option is set
  • oauth2_grant_type: the OAuth2 grant type; ignored if the token option is set; possible values:
    • authorization_code: requires oauth2_client_id, oauth2_client_secret, oauth2_auth_url, as well as oauth2_token_url; note that this grant type cannot be handled automatically but rather must be handled by external code that redirects the user to the authentication server and then updates the connection with token information retrieved
    • client_credentials: requires oauth2_client_id, oauth2_client_secret, as well as oauth2_token_url
    • password: requires a username, password, oauth2_client_id, oauth2_client_secret, as well as oauth2_token_url
  • oauth2_redirect_url: The OAuth2 redirect URL for the authorization_code grant type; ignored if the token option is set. Note that the authorization_code grant type requires external user authorization to acquire an access token; the special value "auto" (the default) is meant to be interpreted by servers that implement OAuth2 authorization code client handling
  • oauth2_refresh_token: An OAuth2 refresh token (complements option token)
  • oauth2_scopes: A list of OAuth2 scopes to request; ignored if the token option is set
  • oauth2_scope_separator_char: A separator character for OAuth2 scopes in URI arguments
  • oauth2_token_args: Extra arguments for OAuth2 token requests to oauth2_token_url; if this option is set as well as oauth2_alt_token_url, then the oauth2_token_url value will be added to this as well when the request is made to the oauth2_alt_token_url
  • oauth2_token_expiry: The expiry date of the token, if known
  • oauth2_token_expiry_hint: A token expiry hint as a value in minutes
  • oauth2_token_url: The token URL OAuth2 flows; ignored if the token option is set
  • oauth2_token_auth_secret_only: Use HTTP basic authentication with the client_secret only when making OAuth2 taken requests
  • oauth2_token_use_basic_auth: Use HTTP basic authentication with the client_id and client_secret when making OAuth2 token requests
  • password: The password for authentication; only used if no username or password is set in the URL and if the username option is also used
  • proxy: The proxy URL for connecting through a proxy
  • redirect_passthru: if True then redirect responses will be passed to the caller instead of processed
  • rest_body_auth_error_check: A hash to check all deserialized bodies in 200 OK server responses for authentication errors
  • send_encoding: a send data encoding option or the value "auto" which means to use automatic encoding; if not present defaults to no content-encoding on sent message bodies (note that the RestClient class will only compress outgoing message bodies over CompressionThreshold bytes in size)
  • swagger: the path to a Swagger 2.0 REST schema file for API validation; only used if validator not provided (see the Swagger module)
  • swagger_base_path: in case a REST validator is used, the base path in the schema can be overridden with this option (applies to any REST validator; not just Swagger validators)
  • timeout: The timeout value in milliseconds (also can be a relative date-time value for clarity, ex: 30s)
  • token: Any bearer token to use for the connection; will be passed as Authorization: Bearer ... in request headers; conflicts with username and password options or authentication credentials in the URL; if this option is set then any OAuth2 options are ignored
  • token_api_key_header: The name of a header to send any token in as an API key
  • token_type: The type of token to use for the Authentication header; ignored if no token option is set
  • update_options: Any update token code to use for the object;
See also
update_options for more information
Parameters
do_not_connectif False (the default), then a connection will be immediately established to the remote server
Exceptions
RESTCLIENT-ERRORinvalid option passed to constructor, unsupported data serialization, etc
Since
  • RestClient 1.2 the send_encoding option was added
  • RestClient 1.4 the validator and swagger options were added

◆ del()

hash< auto > RestClient::RestClient::del ( string  path,
auto  body,
*reference< hash< auto > >  info,
*hash< auto >  hdr 
)

sends an HTTP DELETE request to the REST server and returns the response

Example:
hash<auto> ans = rest.del("/orders/1");
Parameters
paththe URI path to add (will be appended to any root path given in the constructor)
bodyan optional message body to be included in the request; if a value for this parameter is passed to the method, then the body will be serialized according to the serialization rules set in RestClient::constructor()
infoan optional reference to a hash that will be used as an output variable giving a hash of request headers and other information about the HTTP request; see rest-info-format for information about the structure of the hash written to the reference supplied here
hdrany headers to be sent with the request; headers here will override default headers for the object as well
Returns
A hash of headers received from the HTTP server with all key names converted to lower-case; if any message body is included in the response, it will be deserialized to Qore data and assigned to the value of the "body" key
Exceptions
DESERIALIZATION-ERRORthe response body could not be deserialized (unknown Content-Type or invalid serialization)
REST-RESPONSE-ERRORif this exception is thrown by the Qore::HTTPClient::send() call in case of an HTTP response code < 100 or >= 300, the message body is still deserialized if possible and the response information can be retrieved in the info hash output keys as follows:
  • "response-body": the decoded response body
  • "response-body-raw": the raw message body in the response (after any content decoding)
  • "response-code": the HTTP response code given
  • "response-headers": a hash of processed response headers
  • "response-headers-raw": a hash of raw unprocessed response headers
Note that this exception is not raised for HTTP status codes indicating an error if the error_passthru option is set to True

Other exceptions can be thrown by the Qore::HTTPClient::send() call used to make the HTTP request.

See also

◆ doOAuth2LoginRequest()

hash< auto > RestClient::RestClient::doOAuth2LoginRequest ( string  url,
hash< auto >  login,
*reference< hash< auto > >  info 
)
private

Returns the deserialized response body of an OAuth2 authorization / token request.

Since
RestClient 2.0

◆ doRequest()

hash< auto > RestClient::RestClient::doRequest ( string  m,
string  path,
auto  body,
*reference< hash< auto > >  info,
softbool  decode_errors = True,
*hash< auto >  hdr 
)

sends an HTTP request to the REST server and returns the response

Example:
hash<auto> ans = rest.doRequest("DELETE", "/orders/1");
Parameters
mthe HTTP method to be used; case is ignored (if not a valid method an HTTP-CLIENT-METHOD-ERROR exception is raised)
paththe URI path to add (will be appended to any root path given in the constructor)
bodyan optional message body to be included in the request; if a value for this parameter is passed to the method, then the body will be serialized according to the serialization rules set in RestClient::constructor()
infoan optional reference to a hash that will be used as an output variable giving a hash of request headers and other information about the HTTP request; see rest-info-format for information about the structure of the hash written to the reference supplied here
decode_errorsdecode the message body with HTTP error responses and throw an exception based on the message body
hdrany headers to be sent with the request; headers here will override default headers for the object as well
Returns
A hash of headers received from the HTTP server with all key names converted to lower-case; if any message body is included in the response, it will be deserialized to Qore data and assigned to the value of the "body" key
Exceptions
DESERIALIZATION-ERRORthe response body could not be deserialized (unknown Content-Type or invalid serialization)
HTTP-CLIENT-METHOD-ERRORinvalid HTTP method argument passed
REST-RESPONSE-ERRORif this exception is thrown by the Qore::HTTPClient::send() call in case of an HTTP response code < 100 or >= 300, the message body is still deserialized if possible and the response information can be retrieved in the info hash output keys as follows:
  • "response-body": the decoded response body
  • "response-body-raw": the raw message body in the response (after any content decoding)
  • "response-code": the HTTP response code given
  • "response-headers": a hash of processed response headers
  • "response-headers-raw": a hash of raw unprocessed response headers
Note that this exception is not raised for HTTP status codes indicating an error if the error_passthru option is set to True
REST-ACCEPT-ERRORif the message has a validator that indicates that the response message only supports types not supported by the current options or environment

Other exceptions can be thrown by the Qore::HTTPClient::send() call used to make the HTTP request.

See also

◆ doSignedRequest()

hash< auto > RestClient::RestClient::doSignedRequest ( string  shdr,
code  signer,
string  m,
string  path,
auto  body,
*reference< hash< auto > >  info,
softbool  decode_errors = True,
*hash< auto >  hdr 
)

sends a signed HTTP request to the REST server and returns the response

Example:
hash<auto> ans = rest.doSignedRequest("X-Signature", signer, "DELETE", "/orders/1");
Parameters
shdrthe name of the header that will have the signature
signerthe code that will return a signature string to put in the header identified by shdr, the argument to this closure will be a hash with the following keys:
  • path: the URI path that will be used for the request
  • body: the serialized message body string
  • hdr: the headers used for the request (without the header identified by shdr)
mthe HTTP method to be used; case is ignored (if not a valid method an HTTP-CLIENT-METHOD-ERROR exception is raised)
paththe URI path to add (will be appended to any root path given in the constructor)
bodyan optional message body to be included in the request; if a value for this parameter is passed to the method, then the body will be serialized according to the serialization rules set in RestClient::constructor()
infoan optional reference to a hash that will be used as an output variable giving a hash of request headers and other information about the HTTP request; see rest-info-format for information about the structure of the hash written to the reference supplied here
decode_errorsdecode the message body with HTTP error responses and throw an exception based on the message body
hdrany headers to be sent with the request; headers here will override default headers for the object as well
Returns
A hash of headers received from the HTTP server with all key names converted to lower-case; if any message body is included in the response, it will be deserialized to Qore data and assigned to the value of the "body" key
Exceptions
DESERIALIZATION-ERRORthe response body could not be deserialized (unknown Content-Type or invalid serialization)
HTTP-CLIENT-METHOD-ERRORinvalid HTTP method argument passed
REST-RESPONSE-ERRORif this exception is thrown by the Qore::HTTPClient::send() call in case of an HTTP response code < 100 or >= 300, the message body is still deserialized if possible and the response information can be retrieved in the info hash output keys as follows:
  • "response-body": the decoded response body
  • "response-body-raw": the raw message body in the response (after any content decoding)
  • "response-code": the HTTP response code given
  • "response-headers": a hash of processed response headers
  • "response-headers-raw": a hash of raw unprocessed response headers
Note that this exception is not raised for HTTP status codes indicating an error if the error_passthru option is set to True
REST-ACCEPT-ERRORif the message has a validator that indicates that the response message only supports types not supported by the current options or environment

Other exceptions can be thrown by the Qore::HTTPClient::send() call used to make the HTTP request.

See also

◆ doValidatedRequest()

hash< auto > RestClient::RestClient::doValidatedRequest ( string  m,
string  path,
auto  body,
*reference< hash< auto > >  info,
softbool  decode_errors = True,
*hash< auto >  hdr 
)

The same as doRequest() except no schema validation is performed on the request.

Since
RestClient 1.7.2

◆ get()

hash< auto > RestClient::RestClient::get ( string  path,
auto  body,
*reference< hash< auto > >  info,
*hash< auto >  hdr 
)

sends an HTTP GET request to the REST server and returns the response

Example:
hash<auto> ans = rest.get("/orders/1?info=verbose");
Parameters
paththe URI path to add (will be appended to any root path given in the constructor)
bodyan optional message body to be included in the request; if a value for this parameter is passed to the method, then the body will be serialized according to the serialization rules set in RestClient::constructor(); note that sending a message body with an HTTP GET request is not standards compliant; see HTTP GET Requests With a Message Body for more information; for maximum compatibility, use NOTHING for this argument when calling this method
infoan optional reference to a hash that will be used as an output variable giving a hash of request headers and other information about the HTTP request; see rest-info-format for information about the structure of the hash written to the reference supplied here
hdrany headers to be sent with the request; headers here will override default headers for the object as well
Returns
A hash of headers received from the HTTP server with all key names converted to lower-case; if any message body is included in the response, it will be deserialized to Qore data and assigned to the value of the "body" key
Exceptions
DESERIALIZATION-ERRORthe response body could not be deserialized (unknown Content-Type or invalid serialization)
REST-RESPONSE-ERRORif this exception is thrown by the Qore::HTTPClient::send() call in case of an HTTP response code < 100 or >= 300, the message body is still deserialized if possible and the response information can be retrieved in the info hash output keys as follows:
  • "response-body": the decoded response body
  • "response-body-raw": the raw message body in the response (after any content decoding)
  • "response-code": the HTTP response code given
  • "response-headers": a hash of processed response headers
  • "response-headers-raw": a hash of raw unprocessed response headers
Note that this exception is not raised for HTTP status codes indicating an error if the error_passthru option is set to True

Other exceptions can be thrown by the Qore::HTTPClient::send() call used to make the HTTP request.

See also

◆ getDefaultHeaders()

hash< auto > RestClient::RestClient::getDefaultHeaders ( )

returns the hash of default headers to sent in all requests

Example:
hash<auto> h = rest.getDefaultHeaders();
Returns
the hash of default headers to sent in all requests
Note
default headers can be set in the constructor and in addDefaultHeaders()
See also
RestClient::addDefaultHeaders()
Since
RestClient 1.3

◆ getNewToken()

hash< auto > RestClient::RestClient::getNewToken ( )

Get a new token from the server either with an OAuth2 token request or using the refresh token.

Returns
The response from the token call
Exceptions
AUTH-CONFIG-ERRORThe RestClient is not configured for token retrieval

The \ oauth2_grant_type option must be set on the client, or an exception will be thrown

Exceptions
AUTH-CONFIG-ERRORcannot retrieve an OAuth2 token without OAuth2 option configuration
Since
RestClient 2.2

◆ getNewTokenIntern()

hash< auto > RestClient::RestClient::getNewTokenIntern ( *reference< hash< auto > >  info)
private

Get a new token from the server.

Since
RestClient 2.2

◆ getOAuth2AuthHeaders()

*hash< auto > RestClient::RestClient::getOAuth2AuthHeaders ( )
private

Returns headers to use with OAuth2 authorization / token requests.

Since
RestClient 2.0

◆ getOAuth2LoginInfo()

hash< auto > RestClient::RestClient::getOAuth2LoginInfo ( string  grant_type)
private

Returns an OAuth2 login hash.

Since
RestClient 2.0

◆ getOAuth2Options()

hash< auto > RestClient::RestClient::getOAuth2Options ( )

Return OAuth2 options.

Returns
a hash of OAuth2 options
Since
RestClient 2.2

◆ getOAuth2RefreshInfo()

hash< auto > RestClient::RestClient::getOAuth2RefreshInfo ( )
private

Returns an OAuth2 refresh hash.

Since
RestClient 2.0

◆ getScopeString()

static *string RestClient::RestClient::getScopeString ( *list< auto >  scopes,
string  separator = ' ' 
)
static

Returns a scope string URI argument.

Parameters
scopesthe list of scopes to use
separatorthe separator string to use
Since
RestClient 2.2

◆ getSendEncoding()

*string RestClient::RestClient::getSendEncoding ( )

returns the current data content encoding (compression) object or NOTHING if no encoding option is set

Example:
*string ce = rest.getSendEncoding();
Returns
the current data content encoding (compression) object or NOTHING if no encoding option is set; see EncodingSupport for valid options
See also
Since
RestClient 1.3

◆ getSerialization()

string RestClient::RestClient::getSerialization ( )

returns the current data serialization format currently in effect for the object

Example:
string ser = rest.getSerialization();
Returns
the current data serialization format currently in effect for the object (see DataSerializationOptions for possible values)
See also

◆ getToken()

*string RestClient::RestClient::getToken ( )

Returns any token set for the connection.

Since
RestClient 2.0

◆ getTokenType()

string RestClient::RestClient::getTokenType ( )

Returns the token type for any token.

Since
RestClient 2.0

◆ getUpdateOptionsAfterLogin()

*hash< auto > RestClient::RestClient::getUpdateOptionsAfterLogin ( hash< auto >  h,
*bool  refresh 
)
private

Returns options to update after an OAuth2 login.

Since
RestClient 2.0

◆ getValidator()

RestSchemaValidator::AbstractRestSchemaValidator RestClient::RestClient::getValidator ( )

returns the current validator object

Returns
the current validator object
Since
RestClient 1.4

◆ gotOAuth2LoginInfo()

hash< auto > RestClient::RestClient::gotOAuth2LoginInfo ( hash< auto >  h,
*bool  refresh 
)

Called when OAuth2 login information has been received.

@bool refresh used to distinguish an initial login or new information from a token refresh

Since
RestClient 2.0

◆ isAuthTokenError()

bool RestClient::RestClient::isAuthTokenError ( int  status_code,
hash< auto >  headers,
*bool  body_deserialized,
*string  body_content_type,
auto  body 
)

Returns True if the response was related to an authorization token error.

Returns
True if the response was related to an authorization token error
Since
RestClient 2.2

◆ loginIntern()

hash< auto > RestClient::RestClient::loginIntern ( *reference< hash< auto > >  info)
private

Authenticates with OAuth2 if configured.

Since
RestClient 2.0

◆ oauth2Auth()

hash< auto > RestClient::RestClient::oauth2Auth ( hash< auto >  login,
*reference< hash< auto > >  info,
*bool  refresh 
)
private

Perform OAuth2 authentication.

Since
RestClient 2.0

◆ oauth2AuthIntern()

hash< auto > RestClient::RestClient::oauth2AuthIntern ( hash< auto >  login,
*reference< hash< auto > >  info,
*bool  refresh 
)
private

Perform OAuth2 authentication.

Since
RestClient 2.0

◆ patch()

hash< auto > RestClient::RestClient::patch ( string  path,
auto  body,
*reference< hash< auto > >  info,
*hash< auto >  hdr 
)

sends an HTTP PATCH request to the REST server and returns the response

Example:
hash<auto> ans = rest.patch("/orders/1", ("action": "cancel"));
Parameters
paththe URI path to add (will be appended to any root path given in the constructor)
bodyan optional message body to be included in the request; if a value for this parameter is passed to the method, then the body will be serialized according to the serialization rules set in RestClient::constructor()
infoan optional reference to a hash that will be used as an output variable giving a hash of request headers and other information about the HTTP request; see rest-info-format for information about the structure of the hash written to the reference supplied here
hdrany headers to be sent with the request; headers here will override default headers for the object as well
Returns
A hash of headers received from the HTTP server with all key names converted to lower-case; if any message body is included in the response, it will be deserialized to Qore data and assigned to the value of the "body" key
Exceptions
DESERIALIZATION-ERRORthe response body could not be deserialized (unknown Content-Type or invalid serialization)
REST-RESPONSE-ERRORif this exception is thrown by the Qore::HTTPClient::send() call in case of an HTTP response code < 100 or >= 300, the message body is still deserialized if possible and the response information can be retrieved in the info hash output keys as follows:
  • "response-body": the decoded response body
  • "response-body-raw": the raw message body in the response (after any content decoding)
  • "response-code": the HTTP response code given
  • "response-headers": a hash of processed response headers
  • "response-headers-raw": a hash of raw unprocessed response headers
Note that this exception is not raised for HTTP status codes indicating an error if the error_passthru option is set to True

Other exceptions can be thrown by the Qore::HTTPClient::send() call used to make the HTTP request.

See also

◆ post()

hash< auto > RestClient::RestClient::post ( string  path,
auto  body,
*reference< hash< auto > >  info,
*hash< auto >  hdr 
)

sends an HTTP POST request to the REST server and returns the response

Example:
hash<auto> ans = rest.post("/orders", ("product": "xyz123", "options": 500));
Parameters
paththe URI path to add (will be appended to any root path given in the constructor)
bodyan optional message body to be included in the request; if a value for this parameter is passed to the method, then the body will be serialized according to the serialization rules set in RestClient::constructor()
infoan optional reference to a hash that will be used as an output variable giving a hash of request headers and other information about the HTTP request; see rest-info-format for information about the structure of the hash written to the reference supplied here
hdrany headers to be sent with the request; headers here will override default headers for the object as well
Returns
A hash of headers received from the HTTP server with all key names converted to lower-case; if any message body is included in the response, it will be deserialized to Qore data and assigned to the value of the "body" key
Exceptions
DESERIALIZATION-ERRORthe response body could not be deserialized (unknown Content-Type or invalid serialization)
REST-RESPONSE-ERRORif this exception is thrown by the Qore::HTTPClient::send() call in case of an HTTP response code < 100 or >= 300, the message body is still deserialized if possible and the response information can be retrieved in the info hash output keys as follows:
  • "response-body": the decoded response body
  • "response-body-raw": the raw message body in the response (after any content decoding)
  • "response-code": the HTTP response code given
  • "response-headers": a hash of processed response headers
  • "response-headers-raw": a hash of raw unprocessed response headers
Note that this exception is not raised for HTTP status codes indicating an error if the error_passthru option is set to True

Other exceptions can be thrown by the Qore::HTTPClient::send() call used to make the HTTP request.

See also

◆ prepareToSend()

RestClient::RestClient::prepareToSend ( string  method,
reference< string >  path,
reference< auto >  body,
*reference< hash< auto > >  hdr 
)

Prepares and processes message parameters for sending without sending the message.

Parameters
methodthe HTTP method to use @path a reference to the URI path @path body a reference to any message body @path hdr a reference to any headers to send
Since
RestClient 1.10.2

◆ preprocessRequestBody()

auto RestClient::RestClient::preprocessRequestBody ( auto  request_body)

Preprocesses the request body before serialization.

The default is to return the request body unchanged

Since
RestClient 2.2

◆ processRestResponse()

hash< auto > RestClient::RestClient::processRestResponse ( hash< auto >  resp,
string  method,
string  path,
*reference< hash< auto > >  info 
)

Process the raw REST response received.

Parameters
respthe return value from HTTPClient::send()
methodthe HTTP method used
paththe URI path used
infoan optional info hash reference for information about the call
Returns
resp with additional or processed information

◆ put()

hash< auto > RestClient::RestClient::put ( string  path,
auto  body,
*reference< hash< auto > >  info,
*hash< auto >  hdr 
)

sends an HTTP PUT request to the REST server and returns the response

Example:
hash<auto> ans = rest.put("/orders/1", ("action": "cancel"));
Parameters
paththe URI path to add (will be appended to any root path given in the constructor)
bodyan optional message body to be included in the request; if a value for this parameter is passed to the method, then the body will be serialized according to the serialization rules set in RestClient::constructor()
infoan optional reference to a hash that will be used as an output variable giving a hash of request headers and other information about the HTTP request; see rest-info-format for information about the structure of the hash written to the reference supplied here
hdrany headers to be sent with the request; headers here will override default headers for the object as well
Returns
A hash of headers received from the HTTP server with all key names converted to lower-case; if any message body is included in the response, it will be deserialized to Qore data and assigned to the value of the "body" key
Exceptions
DESERIALIZATION-ERRORthe response body could not be deserialized (unknown Content-Type or invalid serialization)
REST-RESPONSE-ERRORif this exception is thrown by the Qore::HTTPClient::send() call in case of an HTTP response code < 100 or >= 300, the message body is still deserialized if possible and the response information can be retrieved in the info hash output keys as follows:
  • "response-body": the decoded response body
  • "response-body-raw": the raw message body in the response (after any content decoding)
  • "response-code": the HTTP response code given
  • "response-headers": a hash of processed response headers
  • "response-headers-raw": a hash of raw unprocessed response headers
Note that this exception is not raised for HTTP status codes indicating an error if the error_passthru option is set to True

Other exceptions can be thrown by the Qore::HTTPClient::send() call used to make the HTTP request.

See also

◆ refreshTokenIntern()

hash< auto > RestClient::RestClient::refreshTokenIntern ( *reference< hash< auto > >  info)
private

Gets a new token using the refresh token.

Returns
the response from the refresh token call
Since
RestClient 2.2

◆ replaceDefaultHeaders()

RestClient::RestClient::replaceDefaultHeaders ( *hash< auto >  hdr)

replaces default headers

Parameters
hdrThe headers to set; DefaultHeaders will be added to this hash to set the default headers for the object
Since
RestClient 2.0

◆ requiresOAuth2Token()

bool RestClient::RestClient::requiresOAuth2Token ( )

Returns True if the client requires an OAuth2 token.

Since
RestClient 2.0

◆ requiresRefresh()

bool RestClient::RestClient::requiresRefresh ( )

Returns True if the client requires a tokenm refresh.

Since
RestClient 2.2

◆ setAltTokenSigner()

RestClient::RestClient::setAltTokenSigner ( code  signer,
string  signer_header 
)

Sets alt token signer code and the header for it.

Since
RestClient 2.2

◆ setContentEncoding()

RestClient::RestClient::setContentEncoding ( string  enc = 'auto')

sets the request and desired response encoding for the object; see EncodingSupport for valid options

Example:
rest.setContentEncoding("gzip");
Parameters
encthe data content encoding (compression) option for requests and the desired response content encoding for the object; see EncodingSupport for valid options; if the value "auto" is passed then "gzip" encoding is used for outgoing requests and requested for responses
Exceptions
RESTCLIENT-ERRORinvalid or unsupported data content encoding / compression option
See also
Since
RestClient 1.3

◆ setOAuth2LoginInfo()

RestClient::RestClient::setOAuth2LoginInfo ( hash< auto >  h)
private

Sets options from the OAuth2 login response on the local object.

Since
RestClient 2.0

◆ setOAuth2Options()

RestClient::RestClient::setOAuth2Options ( hash< auto >  new_opts)

Sets OAuth2 options.

Parameters
new_optsa hash of OAuth2 options for the object
Since
RestClient 2.1

◆ setSendEncoding()

RestClient::RestClient::setSendEncoding ( string  enc = 'auto')

change the data content encoding (compression) option for the object

Example:
rest.setSendEncoding("gzip");

The default is to send requests unencoded/uncompressed.

Parameters
encthe data content encoding (compression) option for the object; see EncodingSupport for valid options; if the value "auto" is passed then "gzip" encoding is used
Exceptions
RESTCLIENT-ERRORinvalid or unsupported data content encoding / compression option
See also

◆ setSerialization()

RestClient::RestClient::setSerialization ( string  data = 'auto')

change the serialization option for the object; see DataSerializationOptions for valid options

Example:
rest.setSerialization("yaml");
Parameters
datathe serialization option for the object; see DataSerializationOptions for valid options
Exceptions
RESTCLIENT-ERRORinvalid or unsupported serialization option
See also

◆ setToken()

RestClient::RestClient::setToken ( string  token_type,
string  token,
*string  refresh_token,
*date  token_expiry 
)

Sets a token for authentication.

Since
RestClient 2.0

◆ setupAuth()

RestClient::RestClient::setupAuth ( hash< auto >  opts,
*bool  no_exceptions 
)
private

Sets up authentication info.

Since
RestClient 2.0

◆ setValidator()

RestClient::RestClient::setValidator ( RestSchemaValidator::AbstractRestSchemaValidator  validator)

Sets a new REST schema validator.

Since
RestClient 2.0

◆ startOAuth2AuthPoll()

AbstractPollOperation RestClient::RestClient::startOAuth2AuthPoll ( hash< auto >  login)
private

Starts a non-blocking I/O operation to authenticate with an OAuth2 server and acquire an auth token.

Since
RestClient 2.0

◆ startOAuth2PollRefreshToken()

AbstractPollOperation RestClient::RestClient::startOAuth2PollRefreshToken ( )

Starts an OAuth2 refresh token request in a non-blocking I/O operation.

Since
RestClient 2.0

◆ startOAuth2PollSendRecv()

AbstractPollOperation RestClient::RestClient::startOAuth2PollSendRecv ( )

Starts an OAuth2 token request in a non-blocking I/O operation.

Since
RestClient 2.0

◆ usingOAuth2()

bool RestClient::RestClient::usingOAuth2 ( )

Returns True if the client is configured for authentication with OAuth2.

Since
RestClient 2.0

Member Data Documentation

◆ DataSerializationOptions

const RestClient::RestClient::DataSerializationOptions = ...

Data serialization options; this is a hash to simulate a set of strings.

Data serialization options are as follows:

  • "auto": prefers in this order: json, yaml, rawxml, xml, url, and text
  • "bin": for binary message bodies without data serialization
  • "json": use only JSON serialization
  • "rawxml": use raw XML serialization
  • "text": use only plain text. No serialization is used.
  • "url": for URL-encoded message bodies
  • "xml": use only XML-RPC serialization
  • "yaml": use only YAML serialization

◆ EncodingSupport

const RestClient::RestClient::EncodingSupport = ...

Send content encoding options.

Send content encoding options are as follows:

  • "bzip": use bzip2 compression
  • "gzip": use gzip compression
  • "deflate": use deflate compression
  • "identity": use no content encoding

◆ oauth2_app

string RestClient::RestClient::oauth2_app
private

OAuth2 app name.

To be used by external programs handling OAuth2 calls for this client

◆ oauth2_pkce

bool RestClient::RestClient::oauth2_pkce = False
private

If PKCE should be used with the OAuth2 authorization_code flow.

To be used by external programs handling OAuth2 calls for this client

◆ OAuth2GrantOptions

const RestClient::RestClient::OAuth2GrantOptions = ...

Option requirements per OAuth2 grant type.

Note
the authorization_code grant type cannot be handled automatically