Jump to content

- PBXWebRequest

- # PBXWebRequest

  Followers 0

  Lua → VBScript SwxWare v13.10

  In order to communicate from ECR scripts with web services of all kinds, the Lua integration offers a dynamically embeddable module based on the proven curl library. This module is not loaded by default because this does not unnecessarily increase the resource requirements of the Lua runtime environment.

  Functions offered by this module

  - Execute all well-known request types:
    GET, POST, PUT, PATCH, DELETE und HEAD
  - Support of most common HTTP-Auth methods:
    Basic, Digest und Bearer
  - Add any header to the request in text form
  - Add any URL parameter with build-in escaping
  - Retrieve all header from requests and reponses
  - Automatic conversion of the response body to a Lua string based on the 'Contenttype' header

  Requests can be made either via encrypted or unencrypted connections. This is selected by URL ("https:// ..." oder "http:// ...").

  In addition, certificate validation can be disabled in the case of internal web services with self-signed certificates.

  Howto use the module

  The integration into an ECR script is done with the usual Lua mechanism by means of the keyword 'require' placed in an 'InsertScript'-Block

      local webreq = require "PBXWebRequest"

  The webreq object now can be used to create one or more independent HTTP session objects. New HTTP session objects are preset to HTTP Verb GET with no authentication and certification validation is active.

  Additional note: the webreq should always be checked for 'nil' to avoid potential run-time errors.

      if (webreq ~= nil) then
      	local hsession1, hsession2
      	hsession1 = webreq.new()
      	hsession2 = webreq.new() -- a second HTTP Session object to perform an additional query in parallel
      end

  Here is an example as overview - the detailed description of the API can be found below this example.

      local webreq = require "PBXWebRequest"
      if (webreq ~= nil) then

          local hsession, reponseCode, responseHeaders, encodedURL

          PBXScript.OutputTrace("Web request loaded...")
          hsession = webreq.new()

          hsession:URL("https://example.org")
          hsession:HttpVerb(PBXHttpVerbGet)

          hsession:AddHeader("Content-Type:application/json; charset=UTF-8")

          hsession:AddQueryPair("artist", "Simon & Garfunkel")
          hsession:AddQueryPair("callid", PBXCall.CallId())
          hsession:AddQueryPair("callernumber", PBXCall.CallingPartyNumber())
          hsession:AddQueryPair("callername", PBXCall.CallingPartyName())
          -- hsession:HttpAuth = HttpAuthBasic
          -- hsession:AuthUser = "foo"
          -- hsession:AuthPass = "bar"

          hsession:VerifyPeer(true)

          requestHeaders = hsession:RequestHeaders()
          for i = 1, #requestHeaders do
             PBXScript.OutputTrace(" [" .. i .. "] " .. requestHeaders[i])
          end

          responseCode = hsession:Execute()
          PBXScript.OutputTrace("Web request response " .. responseCode)

          if (responseCode == 200) then
              responseHeaders = hsession:ResponseHeaders()
              for i = 1, #responseHeaders do
                 PBXScript.OutputTrace(" [" .. i .. "] " .. responseHeaders[i])
              end
          end
      end

  A complete usage example can be found in the Zendesk Integration project (incl. Json formatted data handling), which is part of the Open ECR Extensions project here on Swyx Forum.

  Another more simple example is the LaunchHTTPRequest() function from the Function Collection.

  Description of WebReq Object API

  Some enum values used as parameter

  HTTP Verbs

  PBXHttpVerbGetto execute a GET request (default)

  PBXHttpVerbPost to execute a POST request

  PBXHttpVerbPut to execute a PUT request

  PBXHttpVerbDelete to execute a DELETE request

  PBXHttpVerbPatch to execute a PATCH request

  PBXHttpVerbHead to execute a HEAD request

  HTTP Authentication

  PBXHttpAuthNone no authentication used for request (Default)

  PBXHttpAuthBasic HTTP basic authentication by username and password according to RFC7617

  PBXHttpAuthDigest HTTP digest authentication by username and password according to RFC7616

  PBXHttpAuthBearer HTTP bearer authentication by OAuth 2.0 bearer access token provided via password property

  PBXHttpAuthAny automatic negotiation which authentication mechanism to use

  API Methods

  The following methods set the respective value when it is passed as a parameter, or return the current value set if the method is called without parameters. Note: all examples assume a HTTP session variable with the name hsession!

  HttpVerb(<verb enum>)

  Set HTTP Verb by enum value.

  To set:

      hsession:HttpVerb(PBXHttpVerbPost)

  To retrieve:

      verb = hsession:HttpVerb()

  HttpAuth(<auth enum>)

  Set HTTP authentication method to use.

  To set:

      hsession:HttpAuth(PBXHttpAuthBasic)

  To retrieve:

      auth = hsession:HttpAuth()

  AuthUser("<user name>")

  Set user name to use with authentication.

  To set:

      hsession:AuthUser("<user name>")

  To retrieve:

      user = hsession:AuthUser()

  AuthPass("<password>")

  Set password to use with authentication.

  To set:

      hsession:AuthPass("<password>")

  To retrieve:

      password = hsession:AuthPass()

  VerifyPeer(<true/false>)

  Activate or deactivate validation of TLS certificate. 'true' = check is active, 'false' = check is deactivated.

      hsession:VerifyPeer(false)

  Url("<url string >")

  Sets the URL for the request. The choice between encrypted or unencrypted is made via the URL in the form "https:// ..." oder "http:// ...".

  To set:

      hsession:URL("https://example.org")

  To retrieve:

      url = hsession:URL()

  Additional functions

  UrlEncode("<string to encode>")

  Convert given string according to URL escaping rules as of https://en.wikipedia.org/wiki/URL-Encoding

  Return value: string URL encoded

      url_encoded = hsession:URLEncode("Dörte Weiß sucht das Glück")

  AddHeader("<header string>")

  Sets any header as text

  Return value: none

      hsession:AddHeader("Content-Type:application/json; charset=UTF-8")

  AddQueryPair("<key>", "<value>")

  Set key/value pair to use in request URL

  Return value: none

      hsession::AddQueryPair("artist", "Simon & Garfunkel")

  RequestBody("<body text>")

  Sets any request body text or returns the currently set text (blank string if no text has been set)

  To set:

      hsession:RequestBody("<h1>My body text</h1>")

  To retrieve:

      body = hsession:RequestBody()

  RequestHeaders()

  Return current list of request header(s) as Lua table or nil.
  No input parameter supported!

  Return value: Lua table or 'nil'

      headers = hsession:RequestHeaders()

  ResponseBody()

  Return last response body text or blank string.
  No input parameter supported!

      respBody = hsession:ResponseBody()

  ResponseHeaders()

  Return current list of response header(s) as Lua table or nil.
  No input parameter supported!

  Return value: Lua table or 'nil'

      respBody = hsession:ResponseHeaders()

  Execute()

  Execute web request with given parameters.
  No input parameter supported!

  Return value: response code from request as number. Will be 200 on successful request or any value according to HTTP spec.

      resp = hsession:Execute()

  Reset()

  Resets the HTTP Session object back to its initial state. The HTTP verb is GET without authentication and certificate validation is enabled.

  Return value: none

      hsession:Reset()

  Tracing

  To diagnose a problem the following trace modules of SwyxWare-Server can be used:

  - SrvScrAPI set to 6 to get detailed tracing for API calls
  - SrvScrWeb set to 6 to get detailed tracing for any web request

  Final notes

  - Two timeout values are fixed and can‘t be changed dynamically:
    Maximum time for establishing a connection to the web service is 10s.
    Maximum time for web service to respond is 10s
  - The http proxy settings are read and applied by the system.

  By Tom Wellige

  - May 23, 2022
  Share
  Share
  Followers 0

## Important Information

By using this site, you agree to our Terms of Use and have taken note of our Privacy Policy.
We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.